Java异常处理
异常通常包含以下几大类:
- 用户输入了非法数据。
- 要打开的文件不存在。
- 网络通信时连接中断,或者JVM内存溢出。
Exception类的层次
所有异常类都是从java.lang.Exception类继承的子类。
Exception类和Error是Throwable类的子类。
Error用来指示运行时环境发生的错误。
捕获异常
使用try和catch关键字可以捕获异常。
try
{
//程序代码
}catch(ExceptionName e1)
{
//Catch块
}
实例:
例子中声明有两个元素的一个数组,当代码试图访问数组的第三个元素的时候就会抛出一个异常。
import java.io.*;
public class yichang {
public static void main(String[] args){
try{
int a[]=new int[2];
System.out.println("访问第三个元素:"+a[3]);
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("Exception thrown :"+e);
}
System.out.println("Out of the block");
}
}
输出结果:
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3
Out of the block
多重捕获块
语法:
try{
// 程序代码
}catch(异常类型1 异常的变量名1){
// 程序代码
}catch(异常类型2 异常的变量名2){
// 程序代码
}catch(异常类型2 异常的变量名2){
// 程序代码
}
Throws/throw 关键字
如果一个方法没有捕获一个检查性异常,那么该方法必须使用 throws 关键字来声明。throws 关键字放在方法签名的尾部。
也可以使用 throw 关键字抛出一个异常,无论它是新实例化的还是刚捕获到的。
可以同时抛出多个异常,用逗号隔开。
实例:
import java.io.*;
public class className
{
public void withdraw(double amount) throws RemoteException,
InsufficientFundsException
{
// Method implementation
}
//Remainder of class definition
}
finally关键字
finally总会被执行,可以运行清理类型等收尾善后的语句。
语法:
try{
// 程序代码
}catch(异常类型1 异常的变量名1){
// 程序代码
}catch(异常类型2 异常的变量名2){
// 程序代码
}finally{
// 程序代码
}
自定义异常
- 所有异常都必须是Throwable的子类。
- 检查性异常类必须继承Exception类。
- 运行时异常类需要继承RuntimeException类。
例如:
class MyException extends Exception{
}