June 2012
Intermediate to advanced
288 pages
6h 48m
English
throw Statement
A throw statement lets you throw your own exceptions. The throw statement has the following basic format:
throw new exception-class ();
The exception-class can be Exception or a class that’s derived from Exception.
Here’s a snippet of code that demonstrates the basic structure of a method that throws an exception:
public static void doSomething(boolean t)
throws Exception
{
if (t)
throw new Exception();
}
Here, the doSomething method accepts a Boolean value as a parameter. If this value is true, it throws an exception; otherwise, it doesn’t do anything.
Note: If a method contains a throw statement, it must include a throws clause in its declaration.
Read now
Unlock full access