Java Exceptions  «Prev  Next»

Lesson 4Java formalizes exceptions
ObjectiveIdentify whether a Method throws an Exception.

Identify whether Java Method throws an Exception

  1. The way a method indicates that an exception has occurred is by using the keyword throw.
  2. The terminology is that a method throws an exception.
  3. Every method that uses the keyword throw in its body must advertise this fact in its method declaration.
  4. It must hold up a sign and tell the world, not hide it in the depths of its code.
  5. This is how Java formalizes exception handling and makes it part of a class' and method's API.
  6. For example, for the constructor for Integer we were just considering, its full declaration is not

public Integer(String s)

but rather:
public Integer(String s) throws NumberFormatException

NumberFormatException

The constructor makes it very clear that it might report an error by throwing an exception. The type of exception it might throw is a NumberFormatException. You will see an overview of different types of exceptions in just a moment.

Caution regarding Exceptions

If your code does not handle an exception, the Java interpreter provides default behavior, though it may not be what you want. By default, the Java interpreter provides code for any unhandled exception by writing an error message to the standard output and halting the thread that threw the exception, which does not necessarily mean your program will come to a halt. If there is more than one thread currently running, the other threads will continue to run just fine.

If you want to invoke a method that might throw an exception, you must either:
  1. Be prepared to catch it, or
  2. Indicate that your method might, in turn, rethrow the exception
Now let's discuss how to catch exceptions.

A method declaring that it throws a certain exception class may throw instances of any subclass of that exception class.
The code below contains a method doSomething() that throws IOException.
Within the method doSomething(), FileNotFoundException is thrown which is a subclass of IOException.

import java.io.*;
public class TestClass {
 public static void main(String[] args) {
  try {
   TestClass.doSomething();
  } catch (IOException e) {
      e.printStackTrace();
  }
 }
 public static void doSomething() throws IOException {
  System.out.println("Within do something");
    throw new FileNotFoundException();
 }
}