- 异常体系
----| Throwable 所有异常或错误类的超类
--------| Error 错误
--------| Exception 异常
-----------| 编译时异常
-----------| 运行时异常
Throwable常用方法:
tostring() 返回当前异常对象的完整类名+病态信息
getMessage() 返回创建Throwable传入的字符信息
printStackTrace() 打印异常的栈信息
异常处理
方式一:捕获处理
捕获处理格式:
try{
可能发生异常的代码
}catch(捕获的异常类型 变量名){
处理异常的代码
}
捕获处理要注意的细节:
- 如果try块中代码出现了异常经过处理之后,那么try-catch块外面的代码可以正常行。
- 如果try块中代码出现了异常的代码,那么try块中出现异常代码后面的代码时不会执行的。
- 一个try块后面时可以跟多个catch块的,即一个try块可以捕获多种异常的类型。
- 一个try块可以捕获多种异常的类型,但是捕获的异常类型必须从小到大进行捕获,否则编译报错。
class Demo{
public static void main(string[] args){
int[] arr = null;
div(4, 0, arr);
}
public static void div(int a, int b, int[] arr){
int c = 0;
try{
c = a/b; //jvm在运行到这句话的时候发现了异常,那么就会创建一个对应的异常对象
System.out.println("数组的长度:"+ arr.length);
}catch(ArithmeticException e){
System.out.println("异常处理了");
System.out.println("tostring:"+ e.toString());
}catch(NullPointerException e){
System.out.println("出现了空指针异常");
}catch(Exception e){
System.out.println("处理所有异常");
}
System.out.println("c="+c);
}
}
方式二:
抛出处理(throw throws)
抛出处理要注意的细节:
- 如果一个方法的内部抛出了一个异常对象,那么,必须要在方法上声明抛出。
- 如果调用了一个声明抛出异常的方法,那么调用者必须要处理异常。
- 如果一个方法内部抛出了一个异常对象,那么throw语句后面的代码都不会在执行了。
- 在一种情况下,只能抛出一种类型的异常对象。
throw与throws两个关键字:
- throw关键字用于方法内部,throws用于方法声明上的。
- throw关键字是用于方法内部抛出一个异常对象的,throws关键字时用于在方法声明上声明抛出异常类型。
- throw关键字后面只能有一个异常对象,throws后面一次可以声明抛出多种类型的异常。
class Demo{
public static void main(String[] args){
try{
int[] arr = null;
div(4, 0, arr);
}catch(Exception e){
System.out.println("出现异常");
e.printStackTrace();
}
}
public static void div(int a, int b, int[] arr) throws Exception, NullPointerException{
if(b == 0){
throw new Exception(); //抛出一个异常对象
}else if(arr == null){
throw new NullPointerException();
}
int c = a/b;
System.out.println("c="+c);
}
}