Syntax
>>-throw-Expression-;-><
Description
A throw statement causes an exception to be thrown. The result is an
immediate transfer of control that may exit multiple statements, constructor, static and
field initializer evaluations, and method invocations until a try statement
is found that catches the thrown value. If no such try statement is found,
then execution of the thread that executed the throw is terminated after invocation of the
UncaughtException method for the thread group to which the thread belongs.
The Expression in a throw statement must denote a variable or value of a reference type which is assignable to the type Throwable, or a compilation error occurs. Moreover, at least one of the following three conditions must be true, or a compilation error occurs:
If there are any enclosing try statements whose try blocks contain the throw statement, then any finally clauses of those try statements are executed as control is transferred outward, until the thrown value is caught. Note that abrupt completion of a finally clause can disrupt the transfer of control initiated by a throw statement.
If a throw statement is contained in a method declaration, but its value is not caught by some try statement that contains it, then the invocation of the method completes abruptly because of the throw. If a throw statement is contained in a constructor declaration, but its value is not caught by some try statement that contains it, then the the expression that creates the class instance (or the method invocation of method newInstance of class Class) that invoked the constructor completes abruptly because of the throw. If a throw statement is contained in a static initializer, then a compilation check ensures that either its value is always an unchecked exception or its value is always caught by some try statement that contains it. If, despite this check, the value is not caught by some try statement that contains the throw statement, then the value is thrown again if it is an instance of class Error or one of its subclasses; otherwise, it is wrapped in an ExceptionInitializerError object, which is then thrown.
Example
The following is an example of a throw statement:
throw new ACustomExceptionClass("This is the error message");
Syntax diagrams
Java types
throws keyword
try, catch, and finally keywords
Source: The Java Language Specification. Copyright (C) 1996 Sun Microsystems, Inc.