Java throw statement

In this chapter you will learn:

  1. Create and throw an exception
  2. Syntax to throw an exception
  3. Note on Java throw statement
  4. Example - How to use Java throw statement

Description

We can throw an exception in case of an exception.

Syntax

The general form of throw is shown here:


 throw ThrowableInstance; 

Here, ThrowableInstance must be an object of type Throwable or a subclass of Throwable.

Note

There are two ways to 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.

Example

How to use Java throws statement?


public class Main {
  static void aMethod() {
    try {/*  ww  w .  j a  va  2  s.  co m*/
      throw new NullPointerException("demo");
    } catch (NullPointerException e) {
      System.out.println("Caught inside demoproc.");
      throw e; // rethrow the exception
    }
  }

  public static void main(String args[]) {
    try {
      aMethod();
    } catch (NullPointerException e) {
      System.out.println("Recaught: " + e);
    }
  }
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. How to use Java throws statement
  2. Syntax to use Java throws statement
  3. Example - Methods with throws clause
Home »
  Java Tutorial »
    Java Langauge »
      Java Exception Handling
Java Exception
Java Exception types
Java try catch statement
Java throw statement
Java throws statement
Java finally statement
Java Built-in Exceptions
Java custom exception class
Java chained exceptions