• Java_异常处理(Exception)


    异常: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("数组越界");
    }

    }





  • 相关阅读:
    ubuntu 查看进程,查看服务
    ubuntu16.04下配置静态ip
    php监听客户端连接状态
    Excel有用的宏
    openfire插件开发1
    linux ps命令
    转:linux下面/usr/local和opt目录有何区别
    linux 开机自启动软件(包含xampp方法)
    转:java两个jre目录和三个lib目录
    linux PATH环境变量
  • 原文地址:https://www.cnblogs.com/zhouchangyang/p/10584517.html
Copyright © 2020-2023  润新知