异常处理
异常
1.1 异常概述
public class Main{
public static void main(String[] args){
int num1 = 5;
int num2 = 0;
try{
int result = get(num1,num2);
System.out.println("result is " + result);
}
catch(ArithmeticException ex){
System.out.println("error");
}
System.out.println("Ok");
}
public static int get(int x,int y) throws ArithmeticException {
if(y == 0) throw new ArithmeticException("Error number 0");
else return x / y;
}
}
在执行main函数时,进入try,进入get函数,此时y等于0,抛出一个异常,被main函数中catch接收到异常,跳过try中剩下的语句,执行error的输出
输出为:
error
Ok
1.2 异常类型
所有的异常都是Throwable类的子类,Throwable又是Object类的子类。
1.2.1 Error类
Error类是系统错误,由Java虚拟机抛出,这样的错误很少发生,一旦发生,用户只能终止程序
1.2.2 Exception类
Exception类是异常,是由程序和外部环境所引起的错误,可以被捕获和处理
1.2.3 RuntimeException类
RuntimeException类是运行时异常,是程序设计错误,比如错误类型转换,数组越界。
其中RuntimeException、Error以及它们的子类都称为免检异常,可以不用try、catch处理它们
所有其他异常称为必检异常,必须使用try、catch来处理它们
1.3 异常详解
1.3.1 声明异常
每个方法都必须声明它可能抛出的异常的类型,Java不要求显式声明Error和RuntimeExcepton(免检异常),但其他异常必须声明
要声明一个异常就要在方法头中使用关键字throws
例如:
public void Method() throws IOException{
}
声明多个异常时,用逗号分隔
public void Method() throws Exception1,Exception2,Exception3 {
}
1.3.2 抛出异常
检测到的错误程序可以创建一个合适的异常类型并抛出它
例如:
throw new ArithmeticException("Error Message");
其中的“Error Message”可以任意修改,可使用getMessage()方法获取该内容
1.3.3 捕获异常
如果执行完try中的语句没有出现异常,则跳过catch中语句
如果try中的语句抛出异常,如果catch捕获到了异常,则执行catch中的语句,如果catch没捕获到,则会终止程序
1.4 异常类方法
异常也是一个特殊的类,可以调用它的方法来获取信息
方法 | 描述 |
---|---|
+getMessage() | 返回描述该异常对象的信息 |
+toString() | 返回"异常类的全名"+":"+getMessage方法 |
+printStackTrace() | 打印该对象的堆栈信息 |
+getStackTrace() | 赋值给StackTraceElement[]数组该对象的堆栈信息 |
public class Main{
public static void main(String[] args){
try{
System.out.println(sum(new int[] {1,2,3,4,5}));
}
catch(IndexOutOfBoundsException ex){
System.out.println(ex.getMessage());
System.out.println(ex.toString());
System.out.println("--------------");
ex.printStackTrace();
}
}
public static int sum(int[] num) throws IndexOutOfBoundsException {
int sum = 0;
for(int i = 0;i <= num.length;i++){
sum += num[i];
}
return sum;
}
}
输出为:
Index 5 out of bounds for length 5
java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
--------------
java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
at Main.sum(Main.java:20)
at Main.main(Main.java:7)
sum方法后的声明异常可以不写,因为IndexOutOfBoundsException是免检异常
1.5 finally子句
有时候不论是否出现异常都希望执行某些代码,可以使用finally子句来实现
try{
a
}
catch(Exception ex){
b
}
finally{
c
}
1.如果try中没有出现异常则执行a,c
2.如果try出现异常并被catch捕获,则跳过try剩余的语句,执行b,执行c
3.如果try中出现异常但没被catch捕获,则会跳过try剩余的语句,执行c