异常02

异常处理02

关键字:try ,catch,finally,throw,throws

package Study01;

public class Demo01 {
   public static void main(String[] args) {
       int a=1;
       int b=0;
       //假设要捕获多个异常:从小到大!!
       try {//try监控区域
          new  Demo01().a();
          /* System.out.println(a/b);*/

      }catch (Error e) {//catch中填写想要捕获的异常类型
           System.out.println("error异常");
      }catch (Exception e){
           System.out.println("Exception异常");
      }catch (Throwable e){
           System.out.println("Throwable异常");
      } finally {//处理善后,一定会执行
           System.out.println("finally");
      }

        //finally可以不加,IO流,资源关闭

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

package Study01;

public class Demo02 {
   public static void main(String[] args) {
       int a=1;
       int b=0;
       try {
           System.out.println(a/b);
      } catch (Exception e) {
           e.printStackTrace();//打印错误的栈信息
      } finally {//Ctrl+Alt+T快捷键
           System.out.println("快捷键生成的异常处理");
      }
  }


}
package Study01;

public class Demo01 {
   public static void main(String[] args) {
       try {
           new Demo01().Test(1,0);
      } catch (ArithmeticException e) {
           e.printStackTrace();
      }
     /* int a=1;
       int b=0;*/
       //假设要捕获多个异常:从小到大!!
       /*try {//try监控区域
          new Demo01().a();
          *//* System.out.println(a/b);*//*

       }catch (Error e) {//catch中填写想要捕获的异常类型
           System.out.println("error异常");
       }catch (Exception e){
           System.out.println("Exception异常");
       }catch (Throwable e){
           System.out.println("Throwable异常");
       } finally {//处理善后,一定会执行
           System.out.println("finally");
       }*/

        //finally可以不加,IO流,资源关闭

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

      }
       System.out.println(a/b);
  }
}

 

 

posted @ 2021-07-28 15:33  一颗苹果!!  阅读(31)  评论(0)    收藏  举报