1.异常处理的一般结构
try{
}catch(异常类型 对象名){
}finally{
}
处理多个异常时catch(异常类型1 | 异常类型2 对象名)
1.若没有捕捉到异常,贼会抛给调用者
2.catch和finally必须要有一个
3.finally是必执行的,除非JVM直接停止(断电、system.exit(0))
2.thorws和throw用法实例
1.throws
throws用于在方法抛出异常
throw用于手动抛出异常,但仍需要在方法里用throws指定异常类型
private int validateNum(String strNum) throws NumberFormatException,OutNumberBoundException{ try { int num = Integer.parseInt(strNum); if(num<0 || num>3){//自定义异常的使用 throw new OutNumberBoundException("输入有误,必须在0-2之间"); } return num; }catch(NumberFormatException e){ throw new NumberFormatException("你输入的必须是数字"); } }
方法抛出异常后,在调用方法的语句里进行捕捉
int num = -1;
String text = input.nextLine();
try {
num = validateNum(text);
}catch(NumberFormatException e){
System.err.println(e.getMessage());
} catch (OutNumberBoundException e) {
System.err.println(e.getMessage());
}
return num;
}
3.自定义异常
如
public class OutNumberBoundException extends Throwable {继承父类 public OutNumberBoundException(String s) { super(s);调用父类的有参构造(参数s一般是供打印输出的值) } }