1. finally能做什么?
当要把除内存之外的资源恢复到它们的初始状态时,就要用到finally子句。这种需要清理的资源包括:已经打开的文件或网络连接
当要把除内存之外的资源恢复到它们的初始状态时,就要用到finally子句。这种需要清理的资源包括:已经打开的文件或网络连接
2. 子类覆盖父类方法的时候,不能抛出比父类更多的异常
3. 异常处理的一个重要目标是把错误处理的代码同错误发生的地点相分离,这使你能在一段代码中专注于要完成的事情,至于如何处理错误,则放在另一段代码中完成。
4. finally块中避免使用return语句,如果在finally中使用return,会吃掉try catch中的异常信息,屏蔽了错误的发生。
public class TryCatchFinally {
public static final String test() {
String t = "";
try {
t = "try";
int i = 1/0;
return t;
} catch (Exception e) {
// result = "catch";
t = "catch";
return t;
} finally {
t = "finally";
return t;
}
}
public static void main(String[] args) {
System.out.print(TryCatchFinally.test());
}
}
// output: finally
5. finally块中避免再次抛出异常,否则也会吃掉try catch语句块中的异常。
6. 在try catch中return,在finally中对值的修改是不会生效的:
public class TryCatchFinally {
public static final String test() {
String t = "";
try {
t = "try";
return t;
} catch (Exception e) {
t = "catch";
return t;
} finally {
t = "finally";
}
}
public static void main(String[] args) {
System.out.print(TryCatchFinally.test());
}
}
// output: try