java基础学习:异常机制02(Exception)

java基础学习:异常机制02

  • 异常处理机制:

    • 抛出异常

    • 捕获异常

       

  • 异常处理的5个关键词:

    • try ,catch , finally ,throw ,throws

 

  • 代码案例1:

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

           int a =1;
           int b=0;

           //假设要捕获多个异常:从小到大去捕获

           try {//try监控区域
               System.out.println(a/b);
          } catch (Error r) {//catch 捕获异常
               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,假设IO,资源,关闭!
           
           //try..catch快捷键:ctrl+alt+T
      }
    }
  • 代码案例2:

    public class Test2 {

       public static void main(String[] args) {

           int a =1;
           int b=0;

           try {
               new Test2().cat(1,0);//匿名内部类
          } catch (Exception e) {
               e.printStackTrace();
          }


           //try..catch快捷键:ctrl+alt+T
      }


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

    }

     

 

 

posted @ 2022-03-08 11:04  gzs1024  阅读(43)  评论(0)    收藏  举报