异常
1 格式
try {
有可能异常的语句
}catch(异常类型 异常对象){
处理异常
}finally{
异常的出口
}
异常类型举例:
ArrayIndexOutOfBoundsException:索引越界
NullPointerException:空指针异常
catch可以捕获同时多个异常:异常间用 | 连接
catch(ArrayIndexOutOfBoundsException | NullPointerException ){
//....
}
Exception类是所有异常类的父类,因此可以用这个类型表示捕获所有异常:
try{
//...
}
catch(Exception e){
e.printStackTrace; //打印错误路径
}finally{
//一定会执行
//一般用于关闭一些资源,
//如调用Scanner的close方法
}
注意:
将Scanner对象在try的()中创建,就能保证try执行完毕后自动调用Scanner的close方法
try(Scanner sc = new Scanner(System.in){
int num = sc.nextInt();
} catch (Exception e){
e.printStackTrace;
}
)
注意:
异常信息如果在异常发生处没有进行异常处理,那么异常信息就会向上传递,直到main函数中,如果还没有,则交给JVM处理,程序将报错终止;
异常信息主要看第一行。
2 抛出异常信息
使用throw手动抛出异常
public static int fun(int x){
if(x==0){
throw new ArithmeticException("抛出0异常")
}
return 10/x;
}
3 异常说明
将可能发生的异常在方法定义的位置进行标注,用来提醒调用者要捕获这些异常
public fun(int x) throws ArithmeticException{
if(x==0){
throw new ArithmeticException("抛出0异常")
}
}
4 finally的注意事项
public static int func(){
try{
return 10;
}finally{
return 20;//finally尽量不要写return语句
}
}
finally的执行是在方法返回之前,如果try或catch中有return语句,那么会优先执行finally语句,而碰巧finally中也有return语句,那么catch或try中的return语句就会得不到执行。
5 异常体系
- 顶层类Throwable派生出Error和Exception两个子类
- Error是指Java运行时内部错误和资源耗尽错误
- Exception的一个子类
RuntimeException
类和Error
类称为非受查异常(执行时会报错),所有其他异常称为受查异常(编译时会报错)
6 自定义异常类
class Myerror extends Exception{
public Myerror(String s){
super(s);//调用父类的构造方法
}
}
public static void login() throws Myerror{
if(passwd==0){
throw new Myerror("用户名错误");//主动抛出异常
}
}
public static void main(String[] args){
try{
login();
}catch(Myerror e){
e.printStackTrace();
}
}
注意:
- 继承自Exception的异常默认为受查异常
- 继承自RuntimeException的异常默认是非受查异常