最近在学Java异常处理,码一下备忘。
异常和错误的区别和处理方式
首先,错误和异常都是程序运行中出现了问题,错误一般是重大问题,一般与代码无关,最好的处理方式是交给JVM去处理。异常一般是中度或轻度问题,一般跟代码有关。
异常处理方法有两种:
- 处理异常:使用try...catch...代码块来处理,把可能导致异常的代码放入try代码块中,把处理方法放入catch代码块中。
- 声明异常:用throw抛出异常,让改代码的调用者来处理异常,可以在方法名后用throws关键字声明异常类型或者在catch代码块中用throw关键字抛出异常。
几种常见异常
算术异常类:ArithmeticExecption
当除数为0时会出现该异常,用catch代码块处理异常后,程序可以编译通过。
public static void div(int a, int b) {
int x = 0;
try {
x = a / b;
}
catch(java.lang.ArithmeticException e) {
x = 0;
}
finally {
System.out.println(x);
}
}
public static void main(String[] args) {
div(3, 0);
}
空指针异常类:NullPointerException
对空内容进行指针操作会出现该异常
public static void main(String[] args) {
String a = null;
try {
int i = a.indexOf('h');
}
catch (java.lang.NullPointerException e) {
System.out.println(e.fillInStackTrace());
}
}
数组负下标异常:NegativeArrayException
int[] arr = new int[3];
try {
arr[-8] = 0;
}
catch(java.lang.NegativeArraySizeException e){
e.printStackTrace();
}
数组下标越界异常:ArrayIndexOutOfBoundsException
当数组下标超过数组长度会引起该异常
int[] arr = new int[3];
try {
arr[3] = 0;
}
catch(java.lang.ArrayIndexOutOfBoundsException e){
e.printStackTrace();
}
字符串转换为数字异常:NumberFormatException
字符串中带有空格,转换成int类型出现该异常
String num = "123 ";
try {
Integer.parseInt(num);
}
catch (NumberFormatException e) {
e.printStackTrace();
}
网友评论