Java基础--异常

异常

参考:https://www.cnblogs.com/achievement-active/p/9304293.html
检查性异常:用户错误或问题引起的问题,测试解决;
运行时异常:运行时异常实可能被程序员避免的异常;
错误:错误不是异常,而是脱离程序员控制的问题。
image.png

处理异常五个关键字:try、 catch、 finally、 throw、 throws

package exception;
public class Test {
    public static void main(String[] args) {
        int a = 1;
        int b = 0;
        // 要捕获多个异常要从小到大
        // try-catch的快捷键 ctr + alt + t
        try{
            System.out.println(a/b);
            new Test().a();
        }catch (ArithmeticException e) {
            System.out.println("程序出现异常,除数不能为0");
        }catch (Error e ){
            System.out.println("Err,栈溢出");
        }catch (Throwable te){
            System.out.println("Trowable");
        }
        finally {
            System.out.println("finally");
        }


        try {
            new Test().test(1,0);
        } catch (ArithmeticException e) {
            e.printStackTrace();
        } finally {
        }
    }

    public void a(){b();}
    public void b(){a();}

    // 假设这个方法处理不了这个异常,可以在方法上抛出异常
    public void test(int a, int b) throws ArithmeticException{
        if(b == 0){
            throw new ArithmeticException(); //主动抛出异常
        }
    }
}

原文地址:https://www.cnblogs.com/sinlearn/p/13362998.html