zoukankan      html  css  js  c++  java
  • 异常处理

    异常:Exception

    try{

                //捕获异常

        }catch{

               //处理异常

               }

    异常处理机制:

       1.在try块中,如果捕获了异常,那么剩余的代码都不会执行,会直接跳到catch中,

       2.在try之后,必须要跟catch或者finally,写finally后无论上面有没有异常,最后都会执行finally块

    try {
    int a = 1 / 0; //分母异常
    }catch (ArithmeticException e){
    e.printStackTrace(); //处理异常
    }finally { System.out.println("测试finally");
    }

    3.catch块可以有多个,可以嵌套try-catch-finally
             try {
    try {
    int a = 1 / 0;
    }catch (ArithmeticException e){
    e.printStackTrace();
    System.out.println("try嵌套");
    }
    int[] b = new int[10];
    b[20] = 100; //数组越界异常
    }catch (ArithmeticException e){
    //catch: 处理异常
    e.printStackTrace();

    } catch (ArrayIndexOutOfBoundsException e){
    e.printStackTrace();
    System.out.println("数组越界");
    }finally {
                     }
    4.如果不想自己处理异常,可以选择抛出异常(throws Exception),抛出的异常将由调用的方法来处理
    public static void test() throws Exception {            //抛出异常

    //模拟抛出异常

    try {
    int[] b = new int[10];
    b[30] = 29;
    }catch (ArrayIndexOutOfBoundsException e){
    e.printStackTrace();
    throw new Exception("数组越界");
    }

    }





  • 相关阅读:
    tcpcopy用法
    iptable用法
    svn回滚
    J.U.C CAS
    J.U.C JMM. pipeline.指令重排序,happen-before(续)
    J.U.C JMM. pipeline.指令重排序,happen-before(续MESI协议)
    J.U.C JMM. pipeline.指令重排序,happen-before
    J.U.C atomic 数组,字段原子操作
    J.U.C atomic AtomicInteger解析
    J.U.C FutureTask之源码解析
  • 原文地址:https://www.cnblogs.com/xuzhendong-0302/p/10591773.html
Copyright © 2011-2022 走看看