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).

Java Virtual Machine
1)An exception is thrown to indicate an abnormal condition. The normal flow of execution is interrupted
1) An exception is thrown to indicate an abnormal condition. The normal flow of execution is interrupted.

2) If the exception is not caught, the program terminates with an error message.
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.
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. If no finally clause is provided, control is returned after the try-catch statement in which the exception is caught
4) Control is returned to the program at the finally clause of the try-catch statement in which the exception is caught. If no finally clause is provided, control is returned after the try-catch statement in which the exception is caught.


throw Statement in Java

You have only been catching exceptions that are thrown by the Java run-time system. However, it is possible for your program to throw an exception explicitly, using the throw statement. The general form of throw is shown here: throw ThrowableInstance; Here, ThrowableInstance must be an object of type Throwable or a subclass of Throwable. Primitive types, such as int or char, as well as non-Throwable classes, such as String and Object, cannot be used as exceptions. There are two ways you can obtain a Throwable object: using a parameter in a catch clause or creating one with the new operator. The flow of execution stops immediately after the throw statement; any subsequent statements are not executed. The nearest enclosing try block is inspected to see if it has a catch statement that matches the type of exception. If it does find a match, control is transferred to that statement. If not, then the next enclosing try statement is inspected, and so on. If no matching catch is found, then the default exception handler halts the program and prints the stack trace. Here is a sample program that creates and throws an exception. The handler that catches the exception rethrows it to the outer handler.
// Demonstrate throw.
class ThrowDemo {
 static void demoproc() {
  try {
   throw new NullPointerException("demo");
  } 
  catch(NullPointerException e) {
   System.out.println("Caught inside demoproc.");
   throw e; // rethrow the exception
  }
 }
 // ----- main
 public static void main(String args[]){
  try {
   demoproc();
  } 
  catch(NullPointerException e) {
   System.out.println("Recaught: " + e);
  }
 }
}


This program gets two chances to deal with the same error.
1) First, main( ) sets up an exception context and then calls demoproc( ). The demoproc( ) method then sets up another exception-handling context and immediately throws a new instance of NullPointerException, which is caught on the next line. The exception is then rethrown. Here is the resulting output: After running the program you will receive the output.
Caught inside demoproc.
Recaught: java.lang.NullPointerException: demo

The program also illustrates how to create one of Java’s standard exception objects. Pay close attention to this line:
throw new NullPointerException("demo");

Here, new is used to construct an instance of NullPointerException. Many of Java’s built-in run-time exceptions have at least two constructors: one with no parameter and one that takes a string parameter. When the second form is used, the argument specifies a string that describes the exception. This string is displayed when the object is used as an argument to print( ) or println( ). It can also be obtained by a call to getMessage( ), which is defined by Throwable.


Exceptions thrown by methods of Objects in Java

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.


Java 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.

SEMrush Software