1、概念:
Java语言中,将程序执行中发生的不正常情况称为“异常”。(语法错误和逻辑错误不是异常)。
2、异常分类:
1、Error:java虚拟机无法解决的严重问题。如:jvm系统内部错误、资源耗尽等严重情况。是严重错误,程序会崩溃。
StackOverflowError(栈溢出)。
2、Exception:因编程错误或偶然外在因素导致的一般性问题,可以使用针对性的代码进行处理。例如:空指针访问、读取不存在文件、网络连接中断等。
Exception:分为两大类:运行时异常(程序运行时发生的异常)和编译时异常(编译过程中的异常)。
3、异常体系图:
4、常见运行时异常:
1、NullPointerException:空指针异常。
2、AirthmeticException:数学运算异常:如10/0。
3、ArrayIndexOutOfBoundsException:数组下标越界异常。
4、ClassCastException:类型转换异常
5、NumberFormatException:数字格式不正确异常:如将字符串转换为数字
String number = "hsf";
int n1 = Integer.parseInt(name); // 抛出异常
5、异常处理:
5.1、try{} catch{} finally{}方法
1、执行机制
try {
可能会发生异常的代码
抛出异常后,后面的代码不再执行
} catch(Exception e) { // 当异常发生,系统将异常封装为exception对象e,传递给catch
出现了异常,执行catch语句块代码
得到捕获的异常,程序员可以自己处理。是抛出异常还是进行别的处理
如果未发生异常,catch不执行
} finally {
不管是否发生异常,都会执行finally的代码
通常将释放资源代码放在这里(如关闭数据库、关闭文件等)
}
int num1;
int num2;
try {
int res = num1 / num2; // 可能发生异常如 / 0 的情况
} catch(Exception e) {
System.out.println("出现异常的原因:" + e.getMessage()); // 输出异常信息
}
5.2、throws:抛出异常
1、原理:如果某个地方出现异常,他会将该异常的处理往上一级抛出,让上级解决,一直抛到JVM为止,如果直到JVM都没有解决,jvm就会直接输出异常信息,然后推出程序。
6、异常作业:
6.1、cal方法,计算两数相除,对其中的异常进行处理:
public static void main(String[] args) {
try {
// 1、验证传入的参数个数是否正确:
if(args.length != 2) {
throw new ArrayIndexOutOfBoundsException("参数个数不对");
}
int n1 = Integer.parseInt(args[0]);
int n2 = Integer.parseInt(args[1]);
double res = cal(n1, n2); // 该方法可能抛出计算异常
System.out.println("计算结果是:" + res);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println(e.getMessage());
} catch (NumberFormatException e) {
System.out.println("参数格式不正确,需要输出整数");
} catch (AirthmeticException e) {
System.out.println("出现了除0异常");
}
}
public static double cal(int n1, int n2) {
return n1 / n2;
}