Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding return in finally hides the exception

I have the following code

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

    }
}

Which gives the error

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

Which is as expected, but adding a return statement in the finally block makes the error go away

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

Can someone please explain me what is going on? and why the error disappears?

Note : I wrote this code purely for experimental purposes!

like image 404
codeMan Avatar asked Mar 04 '15 18:03

codeMan


1 Answers

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

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

In your original code, your try block could (well, it will) throw Exception (or CustomException in your real code, apparently) - and that's a checked exception, which means you have to either catch it or declare that the method might throw it.

like image 165
Jon Skeet Avatar answered Sep 26 '22 01:09

Jon Skeet