一、概述:
异常指在程序运行时,遇到到的各种不正常的状况。
Java程序在运行时可能遇到的异常可分为两类:
-
Exception
①编译时异常
②运行时异常 -
Error
比Exception更加致命,是Java虚拟机无法解决的严重问题。大多与程序员无关。
Error和Exception的区别是Error是程序无法控制和处理的,当出现这种异常时,Java虚拟机会终止线程;而Exception通常是可以被程序处理的。
异常体系结构:
二、运行时异常举例
- ArithmeticException (算术运算异常)
int a = 10;
int b = 0;
System.out.println(a/b);
- NullPointerException (空指针异常)
int[] array = null;
System.out.println(array[0]);
String str = null;
System.out.println(str.charAt(0));
- ArrayIndexOutOfBoundsException (数组下标越界)
int[] array = new int[5];
System.out.println(array[5]);
三、异常处理
- try - catch - finally
将可能出现异常的代码用try代码块装起来,与其余不会出现异常的代码隔离开。
try{
//监控区域(此处可能出现异常)
}catch (异常类型1 变量名1){//例:(NumberFormatException e)
//捕获异常
//处理异常1的方法
}catch (异常类型2 变量名2){
//处理异常2的方法
}catch (异常类型3 变量名3){
//处理异常3的方法
/*
可以包含多个catch
但要捕获多个异常时,必须要从小到大的捕获
*/
}finally {
//一定会执行的代码
//作用:处理善后工作,可以不写
}
}
快捷键: Ctrl + Alt + T => try/catch/finally
try {
System.out.println(a/b);
} catch (Exception e) { //可以在这里面加入自己的程序
e.printStackTrace(); //打印错误的栈信息
} finally {
}
- throws + 异常类型(可能会出现的异常)
只能写在方法的声明处。当方法体执行时,出现异常则会在异常代码处生成一个异常类的对象,此对象如果满足throws后异常类型是,就会被抛出(抛出不代表解决此异常,最后还是要用try - catch - finally方法来解决异常)。而抛出后的代码将不被执行。
public static void main(String[] args) {
test2();
}
public static void test1() throws ArithmeticException,RuntimeException{
int a = 10;
int b = 0;
System.out.println(a/b);
System.out.println("hhh"); //异常抛出后的代码不执行
}
public static void test2(){
try {
test1();
} catch (RuntimeException e) {
e.printStackTrace();
} finally {
System.out.println("haha");
}
}