Java throw statement
In this chapter you will learn:
- Create and throw an exception
- Syntax to throw an exception
- Note on Java throw statement
- 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:
- How to use Java throws statement
- Syntax to use Java throws statement
- Example - Methods with throws clause