Java异常处理
Java异常处理
异常分为运行时异常RuntimeException和编译时异常,运行时异常不需要处理。
1. try-catch-finally
try{
//可能出现异常的代码
}catch(异常类型1 变量名1){
} //处理异常的方式1
}catch(异常类型2 变量名2){
} //处理异常的方式2
...
[finally{
//一定会执行的代码,就算之前语句中有return 也会执行
//一般进行资源的释放
}]
catch中的异常类型如果满足子父类的关系,则要求子类一定要声明在父类的上面
常用异常对象处理的方式
- e.getMessage() 获取出错信息
- e.printStackTrace() 获取异常链
2. throws
向上一级抛出异常,但到main方法时最好对异常进行处理,否则会继续抛给JVM。
异常代码后续的代码,不会被执行
- 子类重写的方法抛出的异常类型不大于父类被重写的方法抛出的异常类型
public static void method1() throws FileNotFoundException,IOException{
File file = new File("hello1.txt");
FileInputStream fis = new FileInputStream(file);
int data = fis.read();
while(data != -1){
System.out.print((char)data);
data = fis.read();
}
fis.close();
}
3. 手动抛出异常 throw
class Student{
private int id;
public void regist(int id){
if(id >0){
this.id = id;
}else{
throw new RuntimeException("输入非法!");
}
}
}
- throws是处理异常 throw是生成异常
4. 自定义异常
- 继承于现有异常,比如RuntimeException, Exception
- 提供全局常量:serialVersionID
- 提供重载的构造器
public class MyException extends RuntimeException {
static final long serialVersionUID = -7034897190745766939L;
public MyException(){
}
public MyException(String msg){
super(msg);
}
}

浙公网安备 33010602011771号