麦麦脆汁鸡

导航

捕获和抛出异常

捕获

public class Test {
   public static void main(String[] args) {

       int a = 1;
       int b = 0;

       try{
           System.out.println(a/b);
      }//try 监控区域
       
       catch(ArithmeticException e){//catch括号内的参数是 想要捕获的异常类型
           System.out.println("程序出现异常,变量b不能为0");
      }//catch 捕获异常,出现异常就执行catch里面的语句
       
       finally{
           System.out.println("finally");
      }//finally 善后工作,无论有没有异常都会执行

       
       //捕获:try和catch必须要有,finally可以不要
  }
}
  • 假设要捕获多个异常,catch可以写多个,要从小到大!

    catch(Error e){
               System.out.println("Error");
          }
    catch(Exception e){
               System.out.println("Exception");
          }
    catch(Throwable e){
               System.out.println("Throwable");
          }
  • 快捷键:Ctrl + Alt + T

 

抛出

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();//主动抛出异常,一般在方法中使用
      }
       System.out.println(a/b);
  }

}
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();//主动抛出异常,一般在方法中使用
      }
       System.out.println(a/b);
  }

}

 

posted on 2022-03-14 14:19  麦麦脆汁鸡  阅读(36)  评论(0编辑  收藏  举报