zoukankan      html  css  js  c++  java
  • JAVA高级--异常处理概念和异常处理机制

    什么是异常

      程序运行的过程中发生的一些不正常事件

    异常分类

        Throwable

          Error  错误  

          Exception  

            IOException          

            RuntimeException    编程错误    可以不用采用异常处理

    java的异常通过两种机制来处理

    捕获  try-catch-finally

        try 监控   catch  处理   finally  总是执行

    package com.date;
    
    import java.util.InputMismatchException;
    import java.util.Scanner;
    
    public class TryDemo {
      public static void main(String[] args) {
    	System.out.println("请输入一个数字");
    	Scanner input=new Scanner(System.in);
    	int a=input.nextInt();
    	int res=0;
    	try {
    		 res=10/a;
    	}catch (Exception e) {
    		System.out.println(e.getMessage());
    	}finally {//释放资源,比如关闭打开的文件
    		System.out.println("结果为:"+res);
    	}	
    	/*} catch (InputMismatchException e) {
    		System.out.println(e.getMessage());
    		e.printStackTrace();
    	}catch (ArithmeticException e) {
    		System.out.println();
    	}*/
    	
    	
    }
    }
    

      

    抛出 throw,throws

        throw   手动抛出异常(弹出)

        throws  声明方法抛出异常

    package com.date;
    
    public class throwDemo {
       public static void main(String[] args) {
    	   Bar bar=new Bar();
    	  try {
    		  bar.enter(15);
    	} catch (IllegalArgumentException e) {
    		System.out.println(e.getMessage());
    	}
    	 System.out.println("end");  
    }
    }
    
    class Bar{
    	public void enter(int age) throws IllegalArgumentException {
    		if(age<19) {
    			throw new IllegalArgumentException("年龄不合格");
    		}else {
    			System.out.println("欢迎");
    		}
    	}
    }
    

      

    自定义异常

    必须从已有的异常类继承    

     Exception   必须用throws
    package com.date;
    
    public class zidingyiyichDemo {
       public static void main(String[] args) {
    	   Bar1 bar=new Bar1();
    		  try {
    			  bar.enter(18);
    		} catch (AgeLessThanEighteenException e) {
    			System.out.println(e.getMessage());
    		}
    		 System.out.println("end"); 
    }
    }
    
    class AgeLessThanEighteenException extends Exception{
    	private String message;//描述异常信息
    
    	public AgeLessThanEighteenException(String message) {
    		this.message = message;
    	}
    	
    	@Override
    	public String getMessage() {
    		return message;
    	}
    }
    
    class Bar1{
    	public void enter(int age) throws AgeLessThanEighteenException {
    		if(age<19) {
    			throw new AgeLessThanEighteenException("年龄不合格");
    		}else {
    			System.out.println("欢迎");
    		}
    	}
    }
    

      

  • 相关阅读:
    ibatis 批量更新(一)
    eclipse tomcat路径更改后启动报错
    xftp Initialize Flexnet Service failed / Error code: 50003
    百度网盘 文件名中(文件)含有敏感词
    一人之下第二季百度云高清下载
    React Native Mac配置指南
    Androd自己定义控件(三)飞翔的小火箭
    关于职位规划
    SSH框架之Struts(3)——Struts的执行流程之核心方法
    HDU 4891 The Great Pan (字符串处理)
  • 原文地址:https://www.cnblogs.com/tanlei-sxs/p/9955761.html
Copyright © 2011-2022 走看看