-
算数ArithmeticException异常:试图除以0
int b=0; System.out.println(1/b); //error
-
空指针NullPointerException异常
String str = null; System.out.println(str.charAt(0)); //error
-
类型转换ClassCastException异常
Animal d = new Dog(); Cat c = (Cat)d; //error
-
数组越界ArrayIndexOutOfBoundsException异常
int[] arr = new int[5]; System.out.println(arr[5]); //error
-
数字转型NumberFormatException异常
String str2 = "1234abcf"; System.out.println(Integer.parseInt(str2)); //error
异常的处理办法:
package yzy.exception;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class testRuntimeException {
public static void main(String[] args) {
//1. ArithmeticException异常:试图除以0
int b=0;
//System.out.println(1/b); //error
//异常处理:
if(b!=0) {
System.out.println(1/b);
}
//2. NullPointerException异常
String str = null;
//System.out.println(str.charAt(0)); //error
//异常处理: 通常是增加非空判断
if(str != null) {
System.out.println(str.charAt(0));
}
//3. ClassCastException异常
Animal d = new Dog();
//Cat c = (Cat)d; //error
//异常处理: 通常是增加非空判断
if (d instanceof Cat) {
Cat c = (Cat)d;
}
//4. ArrayIndexOutOfBoundsException异常
int[] arr = new int[5];
//System.out.println(arr[5]); //error
//异常处理: 增加关于边界的判断
int a = 3;
if (a < arr.length) {
System.out.println(arr[a]);
}
//5. NumberFormatException异常
String str2 = "1234abcf";
//System.out.println(Integer.parseInt(str2)); //error
//异常处理: 数字格式化异常的解决,可以引入正则表达式判断是否为数字
Pattern p = Pattern.compile("^\\d+$");
Matcher m = p.matcher(str2);
if (m.matches()) { // 如果str2匹配代表数字的正则表达式,才会转换
System.out.println(Integer.parseInt(str2));
}
}
}
class Animal{
}
class Dog extends Animal{
}
class Cat extends Animal{
}
注意事项
-
在方法抛出异常之后,运行时系统将转为寻找合适的异常处理器(exception handler)。潜在的异常处理器是异常发生时依次存留在调用栈中的方法的集合。当异常处理器所能处理的异常类型与方法抛出的异常类型相符时,即为合适的异常处理器。
-
运行时系统从发生异常的方法开始,依次回查调用栈中的方法,直至找到含有合适异常处理器的方法并执行。当运行时系统遍历调用栈而未找到合适的异常处理器,则运行时系统终止。同时,意味着Java程序的终止。
来源:CSDN
作者:云疏不知数
链接:https://blog.csdn.net/qq_43808700/article/details/104149668