The Java compiler is very adept at detecting most errors and alerting us to them before we get to the point of running a program. However, there are errors that the Java compiler is incapable of detecting. In many cases these errors aren't the fault of the programmer.
These kinds of errors are known as exceptions and consist of exceptional situations that a program does not know how to handle.
This module covers the basics of exceptions and shows you how to handle them in your own programs.
Module Learning Objectives
After completing the module, you will have the skills and knowledge necessary to:
Understand the basics of exceptions
Throw an exception in response to an exceptional condition
Execute a section of code and catch any exceptions that it may throw
Use the finally clause to make sure a section of code is executed
In the next lesson, you will get acquainted with exceptions and their significance in Java programming.
Exception Types
Until now, we have focused on explaining the language constructs related to exceptions: the try, catch, multi-catch, finally, and try-with-resources blocks.
You learned the throws clause where you declare that a method can throw certain exceptions. You saw that for some types of exceptions, you
do not need to declare them in the throws clause, but for certain other kinds of exceptions, you can declare them in the throws clause.
Question: Why? What are the different kinds of exceptions?
To answer these questions and get a better idea about the exception handling support in the Java library, we will discuss types of exceptions in this section.
In Java, you cannot throw any primitive types as exception objects. This does not mean that you can throw any
reference type objects as exceptions. The thrown object should be an instance of the class Throwable or one of its subclasses:
Throwable is the apex class of the exception hierarchy in Java. Exception handling constructs such as the throw statement, throws clause,
and catch clause deal only with Throwable and its subclasses. There are three important subclasses of Throwable that you need to learn in detail: the Error, Exception, and RuntimeException classes.
Figure 5-1 provides a high-level overview of these classes.
What will be the output of trying to compile and run the following code?
class App {
public static void main(String[] args) {
try {
throw new IllegalStateException();
} finally {
throw new RuntimeException();
}
}
}
Compilation fails
IllegalStateException is thrown at runtime
RuntimeException is thrown at runtime
Compiles and runs with no output
Answer: C
The finally block always executes just before the method returns.
Since an exception is being thrown from the finally block, it will replace the exception thrown from the try block as the finally block is executed after the try block. This in turn will result in a Run time Exception being thrown.