1,try…catch…finally简单异常处理
-
try …. catch 处理了之后后面的程序可以继续进行。
public class Demo2_Exception {
/**
* * A:异常处理的两种方式
* a:try…catch…finally
* try catch
* try catch finally
* try finally
* b:throws
* B:try...catch处理异常的基本格式
* try…catch…finally
* C:案例演示
* try...catch的方式处理1个异常
try:用来检测异常的
catch:用来捕获异常的
finally:释放资源
世界上最真情的相依就是你在try我在catch,无论你发神马脾气,我都静静接受,默默处理
当通过trycatch将问题处理了,程序会继续执行
*/
public static void main(String[] args) {
Demo2 d = new Demo2();
try{
int x = d.div(10, 0);
System.out.println(x);
}catch(ArithmeticException a) { //ArithmeticException a = new ArithmeticException();
System.out.println("出错了,除数为零了");
}
try …. catch 处理了之后后面的程序可以继续进行。
System.out.println("1111111111111111");
}
}
class Demo2 {
/*
* 除法运算
*/
public int div(int a,int b) { //a = 10,b = 0
return a / b; // 10 / 0 被除数是10,除数是0当除数是0的时候违背了算数运算法则,抛出异常
//new ArithmeticException("/ by zero");
}
}
2,try...catch的方式处理多个异常
-
JDK7以后处理多个异常的方式及注意事项
public class Demo3_Exception {
/**
* * A:案例演示
* try...catch的方式处理多个异常
* JDK7以后处理多个异常的方式及注意事项
*
* 安卓,客户端开发,如何处理异常?try{}catch(Exception e){}
* ee,服务端开发,一般都是底层开发,从底层向上抛
*
* try后面如果跟多个catch,那么小的异常放前面,大的异常放后面,根据多态的原理,如果大的放前面,就会将所有的子类对象接收
* 后面的catch就没有意义了
*/
public static void main(String[] args) {
//demo1();
int a = 10;
int b = 0;
int[] arr = {11,22,33,44,55};
//JDK7如何处理多个异常
try {
System.out.println(a / b);
System.out.println(arr[10]);
} catch (ArithmeticException | ArrayIndexOutOfBoundsException e) {
System.out.println("出错了");
}
}
public static void demo1() {
int a = 10;
int b = 0;
int[] arr = {11,22,33,44,55};
try {
System.out.println(a / b);
System.out.println(arr[10]);
arr = null;
System.out.println(arr[0]);
} catch (ArithmeticException e) {
System.out.println("除数不能为零");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("索引越界了");
} catch (Exception e) { //Exception e = new NullPointerException();
System.out.println("出错了");
}
System.out.println("over");
}
}