java异常处理机制

异常处理机制

  • 抛出异常
  • 捕获异常
  • 异常处理的五个关键字:
    try:尝试处理一些异常,监控区域
    catch:捕获
    finally:无论执不执行,都会走
    throw,throws:抛出异常

代码解释;

        int a=1;
        int b=0;
        System.out.println(a/b);

运行结果:
java异常处理机制_第1张图片

异常处理之后:
代码:

        int a=1;
        int b=0;

        try {  //try监控异常
            System.out.println(a/b);
        }
        catch (ArithmeticException e){     //catch捕获异常
            System.out.println("程序出现计算错误");
        }finally {   //处理善后工作
            System.out.println("finally");
        }

运行结果:
java异常处理机制_第2张图片

  • 假设要捕获多个异常,捕获的顺序要从小到大
    java异常处理机制_第3张图片
    代码:
        int a=1;
        int b=0;


        try {  //try监控异常
            System.out.println(a/b);
        }
        catch (Error e){     //catch捕获异常
            System.out.println("Error");
        }
        catch (Exception e){     //catch捕获异常
            System.out.println("Exception");
        }
        catch (Throwable e){     //catch捕获异常
            System.out.println("Throwable");
        }
        finally {   //处理善后工作
            System.out.println("finally");
        }

运行结果;
java异常处理机制_第4张图片

idea快捷键Ctrl+alt+t,可以直接生成try 、catch ,finally

 public static void main(String[] args) {
        try {
            new Test1().test(1,0);

        } catch (ArithmeticException e) {
            System.out.println("计算错误");
            e.printStackTrace();
        } finally {
            System.out.println("finally");
        }

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

你可能感兴趣的:(初学者,java初学,java,开发语言,后端)