the below code throws compiler error because of line 11. But i assumed that since e is null it wont be handled and it produces no output. Can someone please help me understand the logic behind this program.
Thanks in advance!!
When asking about a compilation error, please tell us what error message you're getting and on what line it was raised.
Because you used the assignment operator on e, e is no longer considered an "effectively final variable" and therefore the compiler can not reason that the only exception type that can possibly be held by e is SQLException. As far as the compiler is concerned, e could be any type that extends Exception.
The m() method declares that it throws SQLException, but line 11 doesn't throw a SQLException, it throws Exception. Exception is not caught or declared, so the compiler raises an error.
One of the key is to understand here is that once a variable is assigned, the compiler doesn't keep track of what value was assigned to it. All it cares about is the type of the variable.
On the throw statement the compiler doesn't know whether ex was assigned null or something else. All it knows is that ex is of type Exception and that you need to handle it.
There are many ways to confirm this behavior, for example the following code:
In the above code when you try to assign sup which is of type Super to sub which is of type Sub (which inherits from Super), the compiler won't allow it. Even though you know the assignment will work (as sup contains an object of type Sub), but when compiler sees the statement Sub sub = sup; all it knows is sup is of type Super and Super is-not-a Sub.