捕获异常和异常处理机制

public class Demo01 {
   public static void main(String[] args) {
       int a =1;
       int b =0;
       //ctrl+alt+T
       //假设要捕获多个异常:从小到大
       try {//监控区域
           new Demo01().a();
      } catch (Error e) {//catch(想要捕获的异常类型) 捕获异常
           System.out.println("Error");
      }catch (Exception e) {//catch(想要捕获的异常类型) 捕获异常
           System.out.println("Exception");
      } catch (Throwable t) {//catch(想要捕获的异常类型) 捕获异常
           System.out.println("Throwable");
      }  finally {//处理善后工作
           System.out.println("final");
      }
       //final 可以不要final ,假设IO,资源,关闭
  }
   public void a(){
       b();
  }
   public void b(){
       a();
  }
}
=========================================================
public class Test2 {
   public static void main(String[] args) {
       try {
           new Test2().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 @ 2024-01-23 11:58  fightownself  阅读(1)  评论(0编辑  收藏  举报