39-异常处理机制
抛出异常
捕获异常
异常处理五个关键字
try、catch、finally、throw、throws
package com.exception;
public class Demo01 {
    public static void main(String[] args) {
       int a = 1;
       int b = 0;
        try {                               //try 监控区域
            System.out.println(a/b);
        } catch (ArithmeticException e) {   //catch() 捕获异常,参数为想要捕获的异常类型
            System.out.println("b不能为0");   //捕获到后会执行这里
        }
        finally {                            //finally 处理善后工作
        }                                    //可以不要
    }
假设要捕获多个异常,增加catch(){}代码块,参数范围从小到大
package com.exception;
public class Demo02 {
    public static void main(String[] args) {
        try {
            new Demo02().a();
        } catch (StackOverflowError e) {
            System.out.println("捕获成功");
        } catch (Error e){
            System.out.println("捕获成功2");
        } catch (Throwable e){
            System.out.println("捕获成功3");
        }
        finally {
        }
    }
    public void a(){
        b();
    }
    public void b(){
        a();
    }
}
选中需要catch的代码,用ctrl+alt+T,直接生成try 、catch、finally
方法内可以用throw抛出异常
package com.exception;
public class Demo03 {
    public static void main(String[] args) {
        new Demo03().test(1,0);
    }
    public void test(int a,int b){
        if(b==0){
            throw new ArithmeticException(); //主动抛出的异常,一般在方法内使用,无论下面是否计算,都会根据if条件主动抛出
        }
        System.out.println(a/b);
    }
}
方法上可以用throws抛出异常
package com.exception;
public class Demo03 {
    public static void main(String[] args) {
        new Demo03().test(1,0);
        
    }
    public void test(int a,int b) throws ArithmeticException {
        System.out.println(a/b);
    }
}
throw和throws的区别如下:
位置不同:throws作用在方法上,后面跟着的是异常的类;而throw作用在方法内,后面跟着的是异常的对象。
功能不同:throws用来声明方法在运行过程中可能出现的异常,以便调用者根据不同的异常类型预先定义不同的处理方式;throw用来抛出封装了异常信息的对象,程序在执行到throw时后续的代码将不再执行,而是跳转到调用者,并将异常信息抛给调用者。也就是说,throw后面的语句块将无法被执行(finally语句块除外)。
 
                    
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号