JAVA练手--异常

1. 基本的

public static void main(String[] args) {
       //1. try catch基本用法
       {
           try{
               int[] intA = new int[2];
               intA[30] = 5;
           }catch(ArrayIndexOutOfBoundsException e){
               //在这里捕获到,但是并没有抛出去
               System.out.print(e);
           }  
       }       
   }

结果:

java.lang.ArrayIndexOutOfBoundsException: 30

2. throw

   public static void main(String[] args) {
       try{
           throw new IOException();
       } catch(IOException e){
           System.out.println("hello");
           e.printStackTrace();
       }
   }

结果:

hello
java.io.IOException                 //这一句和下面一句都是e.printStackTrace();打印出来的
    at tet.kk.main(kk.java:10)

 

3. 异常处理方法

   public static void main(String[] args) {
      try{
          throw new Exception("My Exception");
      }catch(Exception e){
          System.out.println("getMessage         : "+e.getMessage());
          System.out.println("getLocalizedMessage: "+e.getLocalizedMessage());
          System.out.println("getStackTrace      : "+e.getStackTrace());
          System.out.println("getCause           : "+e.getCause());
          System.out.print("printStackTrace    :");
          e.printStackTrace();

      }
   }

结果:

getMessage         : My Exception
getLocalizedMessage: My Exception
getStackTrace      : [Ljava.lang.StackTraceElement;@6d06d69c
getCause           : null
printStackTrace    :java.lang.Exception: My Exception
    at tet.kk.main(kk.java:10)

4. Finally的用法

   public void step1() {
       
       for(int i=0;i<5;i++){
           try{
               step2(i);
           }catch(ArithmeticException e){
               System.out.println("接收到抛过来的异常,不再往外抛了"+e.getMessage());
           }catch(Exception e){
               System.out.println("接收到抛过来的异常,接着往外抛"+e.getMessage());
               new Exception(e.getMessage());
           }
           finally{
               System.out.println("finally  i= "+i+";");
           }
           
       }
   }
   public static void main(String[] args) {
       new kk().step1();
   }
   
   //从runtime的异常中随便拿了两个出来测试
   void step2(int i) throws  ArithmeticException, UnsupportedOperationException{
       //System.out.println(i);
       if(i==2){
           System.out.println("i=2,不进行处理,抛出去");
           throw new ArithmeticException("i=2, step2测试");
       }else if(i==3){
           System.out.println("i=3,不进行处理,抛出去");
           throw new UnsupportedOperationException("i=3, step2测试");
       }
   }

结果:

finally  i= 0;
finally  i= 1;
i=2,不进行处理,抛出去
接收到抛过来的异常,不再往外抛了i=2, step2测试
finally  i= 2;
i=3,不进行处理,抛出去
接收到抛过来的异常,接着往外抛i=3, step2测试
finally  i= 3;
finally  i= 4;
原文地址:https://www.cnblogs.com/maogefff/p/8110402.html