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?
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.
Some common checked exceptions in Java are IOException, SQLException and ParseException.
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.
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 aboveTry this:
try {
....
} catch (RuntimeException e) {
....
}
or if you are expecting both runtime and non-runtime exceptions:
try {
....
} catch (Throwable e) {
....
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With