try {
int i=10/0;
}catch (Exception e){
}
违背基本原则
1.尽量不要捕获通用异常Exception e,捕获特定异常
2.不要忽略异常 catch代码块里要进行错误处理
try {
int i=10/0;
}finally {
}
try {
int i=10/0;
}catch (Exception e){
}finally {
}
try{
int i=10/0;
}catch (NullPointerException ex){
}catch (Exception ex){
}finally {
}
详细异常放前面
每个catch后面都会拼接finally{}
jdk7 try(resource) multiple catch
try(FileReader fileReader=new FileReader("");
FileWriter fileWriter=new FileWriter(""))
{
System.out.println("cc");
}catch (IOException | NullPointerException e){
System.out.println(e);
}
try-catch不要处理程序业务逻辑,捕捉必要的代码段。
产生额外性能开销 异常表 对栈进行快照
常见的运行时异常
NullPointerException -> Integer.parseInt(null)
NumberFormatException ->Double.parseDouble(null)
ClassNotFoundException Class.forName()加载类时没找到
IndexOutOfBoundsException 数组越界
ClassCastException 类型转换错误
NoClassDefFoundError 类加载器加载不到类
异常分类
Throwable
/ \
Exception Error
程序运行中,可以预期的情况 突发的非正常情况,JVM内存溢出
/ \ |
运行时异常 受检查异常 数据库资源没关闭,加载特大图片,递归次数过多
编译时能通过 编译时不通过 要加try-catch 或者throws抛出
int i=10/0; FileReader fileReader=new FileReader("");
throw用在方法体内 表示一定抛出某种异常
throw new NumberFormatException();
如果在方法内用throw抛出某种异常,最好要在方法后用throws抛出异常申明
throws用在方法后面 表示可能会出现的异常 方法调用者处理
public static void main(String[] args) throws FileNotFoundException
finalize
protected void finalize() throws Throwable { }