Java Exceptions  «Prev  Next»
Lesson 1

Introduction to Handling Exceptions in Java

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:
  1. Understand the basics of exceptions
  2. Throw an exception in response to an exceptional condition
  3. Execute a section of code and catch any exceptions that it may throw
  4. 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.

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();

  1. Compilation fails
  2. IllegalStateException is thrown at runtime
  3. RuntimeException is thrown at runtime
  4. 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.