Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Java's Exception class a checked type?

Tags:

java

Here is an example that shows contrary behavior of Java 'Exception' class.

try {

}
catch(Exception ex) {

}

In case of checked type of exception, if we keep a catch block without any error provoking statement to that particular checked exception in try block then, compiler will raise an error like “This exception is never thrown from the try statement body”. But in above case compiler will not give any error.

On the other hand, if we raise an exception of type 'Exception' class by using throw key word, the exception will not be automatically ducked to a caller, like below:

throw new Exception();

In above case compiler gives error like "Unhandled exception type Exception".

So is Java's Exception class a checked or unchecked type?

like image 756
raj Avatar asked Dec 08 '11 05:12

raj


People also ask

Is exception class a checked exception?

Exception hierarchyAll the instances of the Throwable and Exception classes are checked exceptions and the instances if the RuntimeException class are run time exceptions. For example if you create an user-defined exception by extending the Exception class this will be thrown at compile time.

Which of the following is Java's checked exception?

Some common checked exceptions in Java are IOException, SQLException and ParseException.

Which class of exception is not checked?

In Java, exceptions under Error and RuntimeException classes are unchecked exceptions, everything else under throwable is checked. Consider the following Java program. It compiles fine, but it throws ArithmeticException when run. The compiler allows it to compile because ArithmeticException is an unchecked exception.


1 Answers

Stuff you should know about Exceptions:

  • Exceptions are checked, which means if declared as throws, they must be handled (caught). Roughly, these are for "non-programming errors". eg IOException
  • RuntimeExceptions (a subclass of Exception) are unchecked, which means they do not need to be handled if declared, and may be thrown when not declared. Roughly, these are for "programming errors". eg NullPointerException
  • Errors are unchecked, but are not Exceptions (see below). These are for "unrecoverable" errors. eg OutOfMemoryError
  • Throwable is the abstract parent class of all of the above

Try this:

try {
    ....
} catch (RuntimeException e) {
    ....
}

or if you are expecting both runtime and non-runtime exceptions:

try {
    ....
} catch (Throwable e) {
    ....
}
like image 164
Bohemian Avatar answered Oct 13 '22 02:10

Bohemian