注释(用户SOC上的)回答到关于尾调用优化的问题提到了Java 7中有一个称呼,是因为"加ARM的"的"抑制异常",新的功能(适用于ARM CPU的支持?).
在这种情况下,什么是"抑制异常"?在其他情况下,"被抑制的异常"将是一个被捕获然后被忽略的异常(很少是一个好主意); 这显然是不同的.
在Java中使用Readers和Streams总是让我感到困惑的一件事是该close()方法可以抛出异常.因为将close方法放在finally块中是个好主意,这需要一些尴尬的情况.我通常使用这种结构:
FileReader fr = new FileReader("SomeFile.txt");
try {
try {
fr.read();
} finally {
fr.close();
}
} catch(Exception e) {
// Do exception handling
}
Run Code Online (Sandbox Code Playgroud)
但我也看到了这种结构:
FileReader fr = new FileReader("SomeFile.txt");
try {
fr.read()
} catch (Exception e) {
// Do exception handling
} finally {
try {
fr.close();
} catch (Exception e) {
// Do exception handling
}
}
Run Code Online (Sandbox Code Playgroud)
我更喜欢第一个结构,因为只有一个挡块,它看起来更优雅.是否有理由更喜欢第二种或替代结构?
更新:如果我指出两者read并且close只抛出IOExceptions ,它会有所作为吗?因此,在我看来,如果读取失败,关闭将因同样的原因而失败.
我经常遇到这样的情况: -
try{
...
stmts
...
}
catch(Exception ex) {
...
stmts
...
} finally {
connection.close // throws an exception
}
Run Code Online (Sandbox Code Playgroud)
最后还需要一个try-catch块.
克服这个问题的最佳做法是什么?
我运行这段代码:
public class User {
public static void main(String args[]) {
int array[] = new int[10];
int i = 1;
try {
System.out.println("try: " + i++);
System.out.println(array[10]);
System.out.println("try");
} catch (Exception e) {
System.out.println("catch: " + i++);
System.out.println(array[10]);
System.out.println("catch");
} finally {
System.out.println("finally: " + i++);
Object o = null;
o.hashCode();
System.out.println("finally");
}
}
}
Run Code Online (Sandbox Code Playgroud)
结果:
try:1
catch:2
finally:3
在user.main的线程"main"java.lang.NullPointerException中的异常(User.java:17)
在块catch中 - ArrayIndexOutOfBoundsException,但是我们丢失了这个Exception,为什么呢?