Adding a return ultimately hides the exception

I have the following code

public static void nocatch() { try { throw new Exception(); } finally { } } 

What gives an error

 Exception in thread "main" java.lang.Error: Unresolved compilation problem: Unhandled exception type CustomException 

As expected, but adding a return to the finally block causes the error to go away

 public static void nocatch() { try { throw new Exception(); } finally { return; //makes the error go away! } } 

Can someone please explain to me what is going on? and why does the error disappear?

Note: I wrote this code for experimental purposes only!

+6
source share
2 answers

The error disappears because your code is now valid. (Dislike, but valid.)

If the finally block has only a strict return; , then the generic try / catch / finally or try / finally statement cannot throw any exceptions - so you don't need to declare that it can throw an exception.

In your source code, your try block could (well, it will) throw an Exception (or CustomException into your real code, apparently) - and this is a test exception, which means you need to either catch it or declare that the method can throw it .

+7
source

According to javadoc ...

 The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. 

So your code is doing it right.

0
source

Source: https://habr.com/ru/post/983333/


All Articles