java - 是否仅在尝试资源代码中遇到抑制异常?
问题描述
我正在审查 OCP,我偶然发现了这种带有异常的场景。
通常,我们会在 try-with-resource 中遇到 Suppressed Exceptions。如果 try 块和 close() 方法都抛出异常,则只会处理 try 块中的那个。close() 中抛出的异常将被抑制。
我正在尝试其他方法来遇到抑制的异常。跑步methodTwo()
只会扔NullPointerException
。它会被抓住,但不会被压制。怎么了IllegalArgumentException
?
public class Main {
public static void main(String[] args) {
try {
methodTwo();
} catch (Exception e) {
e.printStackTrace();
for(Throwable t : e.getSuppressed()) {
System.out.println(t.getMessage());
}
}
}
static void methodTwo() {
try {
throw new IllegalArgumentException("Illegal Argument");
} finally {
throw new NullPointerException("Null Pointer");
}
}
}
解决方案
正如评论所提到的,如果发生任何异常或返回,最终总是执行。这是因为文件等免费资源的保证。如果您最终不返回或抛出新的异常,它会返回之前设置的异常或值。您也可以更改 finally 块中返回的值,例如:
class A
{
public int value; // it is not good but only for test
}
public class Tester
{
public static void main(String[] args) {
System.out.println(method1().value); // print 10
}
private static A method1() {
A a = new A();
try
{
a.value = 5;
return a;
} finally
{
a.value = 10;
}
}
}
您也可以抛出异常而不是抛出新值并返回值或丢弃最后一个异常。(但所有这些在编程设计中都不好)
当您处理文件时,因为在 java 中没有像 c++ 那样的析构函数(虽然有 finally 但它不同),您必须使用 try finally(或者对于新方法,使用 try-with-resource)来释放从系统获得的资源.
推荐阅读
- java - findFragmentById 在特定活动中返回 null
- python - Python multiprocessing pool making copies of argument list
- android - 对讲呼叫我的内容描述两次
- html - How to insert 2 images and 1 text box on the same row div
- java - Pull data from HashMap and set to attributes in an object
- javascript - Error in serving JSON response with Node.js, MongoDB, and express after 1st response
- c# - Why do I need to convert a list to IEnumerable when the list is already iterable?
- mininet - mininet创建拓扑后,ONOS GUI不显示拓扑
- oop - 如何转换为 OOD
- javascript - Vue.js WebStorm 远程树莓派