in looking at some understanding of grammatical sugar, it is found that both try-with-resources and try-catch-finally have views on abnormal inhibition. Understand the following
try-with-resourcesjava
public static void main(String[] args) {
try {
FileInputStream inputStream = new FileInputStream(new File("test"));
Throwable var2 = null;
try {
System.out.println(inputStream.read());
} catch (Throwable var12) {
var2 = var12;
throw var12;
} finally {
if (inputStream != null) {
if (var2 != null) {
try {
inputStream.close();
} catch (Throwable var11) {
var2.addSuppressed(var11);
}
} else {
inputStream.close();
}
}
}
} catch (IOException var14) {
throw new RuntimeException(var14.getMessage(), var14);
}
}
var2.addSuppressed(var11);
if you encounter an exception when handling external resources (such as reading or writing), and you encounter an exception during the subsequent process of shutting down external resources, you will catch the exception encountered while handling external resources. The exception encountered when closing the resource will be "suppressed" but not discarded. The suppressed exception can be extracted through the getSuppressed method of the exception.
that is, exceptions in catch are handled, while exceptions that occur in closing resources are suppressed (typically, resources are closed in the finally block in try-catch-finally).
and when we have a preliminary understanding of the relevant knowledge of try-catch-finally, we find that there is an exception in finally that will overwrite the exception in catch. The example code is as follows
try {
int a = 5/0;
return 1;
}catch(ArithmeticException amExp) {
throw new Exception("finally");
}finally {
throw new Exception("finalyException");
}
finalyException
if it is understood that under the same function, the syntax sugar writing will make the code more concise and smooth, then has the above changed the functions of both?