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

}





猜你喜欢

转载自www.cnblogs.com/zhouchangyang/p/10584517.html