Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checked Unchecked Exceptions

Tags:

java

exception

Consider the following code

private int meth()
{
   try
   {
       return 1;
   }
   catch(Exception ex)
   {
       return 2;
   }
   finally
   {
       return 3;
   }
}

When the aforeseen code is compiled, "Exception" is treated as unchecked exception. That is "unreachable catch block Exception is never thrown in try block" compilation error does not occur.Consider I am declaring my own exception,

class MyException extends Exception
{
}

and using it in the code

private int meth()
{
   try
   {
      return 1;
   }
   catch(MyException me)
   {
      return 2;
   }
   finally
   {
      return 3;
   }
}

In this "unreachable catch block MyException is never thrown in try block" compilation error occurs. Why in the first scenario "Exception" is treated as RuntimeException and in the second scenario even though "MyException" is a subclass of "Exception" it is being treated as checked exception. Can someone please help me to resolve this issue?

like image 957
jezhilvalan Avatar asked Jul 10 '09 04:07

jezhilvalan


2 Answers

The reason for this behavior is that the only unchecked exceptions in the Java language is RuntimeException and it's subclasses. All other exceptions and errors, including yours since it only subclasses Exception (and not RuntimeException) are checked exceptions.

The reason that the first code example does not get flagged by the compiler, though it uses the Exception class as its catch statement, is because of the class hierarchy. Since all exceptions derive from Exception, you're code isn't catching Exception specifically, but catching all exceptions and casting them to an instance of Exception. Thus, there is no way for the compiler to tell if the exception that will be caught at runtime is a checked or unchecked exception. In the second code block, there is no way for the exception that is caught to not be a checked exception, therefore the compiler can determine that your catch block is unreachable.

like image 143
Peter Avatar answered Sep 30 '22 15:09

Peter


As far as the compiler knows you could at any point get a stack overflow exception, out of memory exception, arithmetic exception, or any number of other JVM-generated exceptions. On the other hand it can statically analyze that try block and see that MyException is never thrown, so it throws its hands up. It knows that it'll never get thrown by the JVM.

like image 29
John Kugelman Avatar answered Sep 30 '22 15:09

John Kugelman