异常

异常

Exception

三大类

  • 检查性异常

  • 运行时异常

  • 错误Error

在java中已经定义了许多异常类

异常处理机制

  • 抛出异常
  • 捕获异常

五个关键字try、catch、finally、throw、throws

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  //throws
            throw new ArithmeticException();//主动抛出异常,一般在方法中使用
        }
    }
}

/*

        int a = 1;
        int b = 0;

        //假设捕获多个异常,从小到大
        try{//监控区域


        }catch(Error e){
            System.out.println("Error");
        }catch (Exception e){
            System.out.println("Exception");
        }catch (Throwable t){
            System.out.println("Throwable");
        }finally{//处理善后工作
            System.out.println("finally");
        }
      //finally 可以不要finally    资源,关闭!
 */
posted @ 2022-06-18 23:29  无双Java  阅读(29)  评论(0)    收藏  举报