异常捕获的通常用法:
try{
可能出现异常的代码(可能有很多。。。)
}catch(异常类型 变量名e){
① 把异常的详细信息打印一下
② 把异常信息保存到磁盘文件 --》 错误日志文件
}finally{
① 此处的代码始终都会执行(系统退出除外)
② 此处一般放关闭流资源(IO部分学习),或者说释放锁(线程部分学习)
③ 不建议在此处放return返回一个值
}
易混淆的情况:
1. 建议
public static void main(String[] args) {
System.out.println(test());
}
public static int test(){
int i= 3;
try {
i = 6;
} catch (Exception e) {
i = 9;
}finally{
i = 100;
}
return i;
}
结果及原因:
返回100,正确做法
2. 不建议
public static void main(String[] args) {
System.out.println(test());
}
public static int test(){
int i= 3;
try {
return i = 6;
} catch (Exception e) {
return i = 9;
}finally{
i = 100;
}
}
结果及原因:
返回6,只要系统没退出,finally都会运行,但是finally没有值返回
3. 不建议
public static void main(String[] args) {
System.out.println(test());
}
public static int test(){
int i= 3;
try {
return i = 6;
} catch (Exception e) {
return i = 9;
}finally{
return i = 100;
}
}
结果及原因:
返回100,只要系统没退出,finally都会运行,且finally最后运行,返回值