Java exception 02 (catch and throw exception)

Exception handling mechanism
1. Throw an exception
2. Catch an exception

Exception handling five keywords
try, catch, finally, throw, throws

Code example:

package com.exception;

public class Test {
    public static void main(String[] args) {
        int a=10;
        int b=0;
        try{//监控区域
            System.out.println(a/b);
        }catch(ArithmeticException e){//捕获异常 catch(想要捕获的异常类型)
            System.out.println("程序出现异常,变量b不能为0");
        }finally{//善后处理工作
            System.out.println("finally");
        }
    }

}

Output sample
Insert picture description here
code example

package com.exception;

public class Test {
    public static void main(String[] args) {
        try{//监控区域
            new Test().a();
        }catch(Error e){//捕获异常 catch(想要捕获的异常类型)
            System.out.println("程序出现异常,栈溢出");
        }finally{//善后处理工作
            System.out.println("finally");
        }
    }
    public void a(){
        b();
    }
    public void b(){
        a();
    }


}

Output example
Insert picture description here
If you want to catch multiple exceptions, the exceptions are from small to large

Shortcut key: control+alt+T
Insert picture description here

Actively throwing exceptions are generally used in methods

Code example:

package com.exception;


public class Test {
    public static void main(String[] args) {
        new Test().test(1,0);
    }
    public void test(int a,int b){
        if(b==0){
            throw new ArithmeticException();
        }
    }
}

Output example
Insert picture description here
Assuming that this method cannot handle the exception, the code example of throws upwards:

package com.exception;


public class Test {
    public static void main(String[] args) {
        try {
            new Test().test(1,0);
        } catch (ArithmeticException e) {
            e.printStackTrace();
        }
    }
    public void test(int a,int b)throws ArithmeticException{
        if(b==0){
            throw new ArithmeticException();
        }
    }
}

Sample output:
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_51224492/article/details/114264542