Java Exceptions  «Prev  Next»

Lesson 3Throwing an exception
ObjectiveFind out How to throw an Exception.

How to throw an Exception

When an exceptional condition is encountered in a Java program, an exception[1] is thrown[2].
Throwing an exception means that a special exception object is created and passed out of the current context. The idea is that a higher context will be more capable of handling the error in response to the exception. The exception object thrown when an exception occurs is ultimately derived from the Throwable class, which is a base class that includes diagnostic methods for obtaining information about an exception.
The Exception class is derived from Throwable and serves as the base class for normal exceptions. More specific exception classes are derived from Exception.

if (obj == null)
  throw new NullPointerException(); 

Handling Exceptions

Once an exception has been thrown, it is up to the programmer to handle the exception or in this case fix a coding error because NullPointerException is actually a runtime exception.
Note: It is worth pointing out that you do not ever directly return an Exception object from a method; instead you must throw it using the throw keyword.


FileInputStream Constructor

The constructor of FileInputStream declares that it throws the exception FileNotFoundException. This FileNotFoundException is derived from the Exception class, hence is a checked exception. With checked exceptions, Java forces you to think about failure conditions and how to handle them. Now, think about the code in Listing 11-13: you are trying to open the file given by the string args[0], which may not be present. If you do not want to catch and handle the FileNotFoundException, you can declare the main() method to throw this exception.

Listing 5-3. CheckedExceptionExample2.java
import java.io.*;
class CheckedExceptionExample2 {
 public static void main(String []args) throws FileNotFoundException {
  FileInputStream fis = new FileInputStream(args[0]);
 }
}

This program will compile fine without any errors. However, this code is still not satisfactory: if you pass the name of a file in the command line that does not exist in the search path, the program will crash after throwing this exception:

D:\ > java CheckedExceptionExample2 somefile.txt
Exception in thread "main" java.io.FileNotFoundException: somefile.txt (The system cannot find the
file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileInputStream.<init>(FileInputStream.java:97)
at CheckedExceptionExample2.main(CheckedExceptionExample2.java:5)


A better way to handle the situation is to throw an error message to the user and inform her that she has to pass the file name as the first argument to the program.

Using Exceptions with Constructors

What will be the output of trying to compile and run the following piece of code?

class Fruit {
  public Fruit() throws Exception {}
  public void eat() throws java.io.IOException{}
}
public class Mango extends Fruit {
  public void eat(){
    System.out.println("Eating Mango");
  }
  public static void main(String [] args) {
    Mango m1 = new Mango();
    m1.eat();
  }
}

  1. Compilation fails due to an error in Fruit
  2. Compilation fails due to an error in Mango
  3. Compiles and throws an Exception at runtime
  4. Compiles and prints Eating Mango

Answer: B
Explanation:
The constructor in Fruit throws an exception. Since Mango extends Fruit, it makes a call to this no-arg constructor through the default constructor provided by the compiler. But the default constructor cannot handle the exception. Hence, an explicit constructor has to be declared in Mango which handles the exception that the super constructor throws. However, the overridden method eat has no error. While overriding a method, the overriding method can choose to not throw any of the exceptions thrown by the overridden method.

[1] Exception: An exceptional situation that a program does not know how to handle is known as an exception. An example of an exception is attempting to divide a number by zero or the system running out of memory.
[2] throw: The throw keyword is used to throw an exception.
br>