Control Flow  «Prev  Next»


Lesson 6The throw statement
ObjectiveCover important points about the throw statement.

Exceptions and throw Statement in Java

An exception[1] is an object that signals that an abnormal event or error has occurred during the course of a program's execution.
Exceptions are thrown by the Java runtime system when an error occurs. These exceptions are referred to as runtime exceptions[2] or unchecked exceptions and are of class java.lang.RuntimeException (or its subclasses).

1) Exception Flow 1 2) Exception Flow 2 3) Exception Flow 3 4) Exception Flow 4

Program 1 Program 2 Program 2 Program 2
  1. An exception is thrown to indicate an abnormal condition.
  2. If the exception is not caught, the program terminates with an error message.
  3. If the exception is caught, exception handling code processes the exception.
  4. Control is returned to the program at the finally clause of the try-catch statement in which the exception is caught.

Java 12 Pogramming
Normal Execution Flow
Exceptions may also be thrown by methods of objects in the Java 1.1 API, other APIs, or the classes that you write. These exceptions are referred to as checked exceptions. The throw statement is used to throw exceptions and tt throws an object that is a subclass of Throwable. The Exception class extends the Throwable class, and in almost all cases, the exceptions that you throw will be subclasses of Exception.

Throws Clause

A method can throw checked exceptions. The clause throws specifies these checked exceptions in the method signature. In the throws clause, you list checked exceptions that a method can throw, so understanding checked exceptions is prerequisite for understanding the throws clause. Since we have covered checked exceptions in the previous section on exception types, we will cover the throws clause now. Let us try reading an integer stored in a file named integer.txt in the current directory. There is an overloaded constructor of the Scanner class that takes a File object as input, so let us try using it. Listing 6-6 shows the program. Will it work?
Listing 6-6. ThrowsClause1.java
import java.io.*;
import java.util.*;
class ThrowsClause1 {
 public static void main(String []args) {
  System.out.println("Reading an integer from the file 'integer.txt': ");
  Scanner consoleScanner = new Scanner(new File("integer.txt"));
  System.out.println("You typed the integer value: " + consoleScanner.nextInt());
 }
}

This code will result in a compiler error of "unreported exception FileNotFoundException; must be caught or declared to be thrown."
If you look at the declaration of this Scanner method, you will see a throws clause:
public Scanner(File source) throws FileNotFoundException {

So, any method that invokes this constructor should either handle this exception or add a throws clause to declare that the method can throw this exception.
Add a throws clause to the main() method; see Listing 6-7
Listing 6-7. ThrowsClause2.java
import java.io.*;
import java.util.*;
class ThrowsClause2 {
 public static void main(String []args) throws FileNotFoundException {
  System.out.println("Reading an integer from the file 'integer.txt': ");
  Scanner consoleScanner = new Scanner(new File("integer.txt"));
  System.out.println("You typed the integer value: " + consoleScanner.nextInt());
 }
}

Classes 1) Error and 2) Exception extend the Throwable class
Classes 1) Error and 2) Exception extend the Throwable class

When an exception is thrown, control transfers to the statement that catches the exception (see next lesson). If the exception is not caught, the program terminates and an error message is displayed on the console window.

The throws clause

When a checked exception is thrown during the course of a method's execution (i.e., by the method or any methods invoked as the result of the method's execution), the exception must be caught within the method or declared in the method's throws clause.
This i*s known as the Catch or Declare rule[3]. This rule does not apply to unchecked exceptions.
If a class overrides a method of any of its superclasses, and that method has a throws clause, then the exceptions in the throws clause of the overriding method must subclass those of the method that is overridden. The overriding method can also catch some or all of these exceptions and eliminate them from its throws clause.

Read File of Integers and sum the Numbers

The following Java program reads in integers and prints the total of the integers in the file.
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Scanner;
import java.util.Locale;

public class ScanSum {
 public static void main(String[] args) throws IOException {
  Scanner s = null;
   double sum = 0;
    try {
     s = new Scanner(new BufferedReader(new FileReader("integer.txt")));
     s.useLocale(Locale.US);
     while (s.hasNext()) {
      if (s.hasNextDouble()) {
       sum += s.nextDouble();
      } else {
       s.next();
      }
     } // end - while
	} finally {
    s.close();
    }
  System.out.println(sum);
 }
}

[1] Exception: An object that signals that an abnormal event or error has occurred.
[2] Rutime exception: An exception that is thrown by the Java runtime system.
[3] Catch or declare rule: If an exception can be thrown during the execution of a method then the method must either catch the exception or declare it in the method's throws clause.