O'Reilly logo

Java, A Beginner’s Guide, 5th Edition by Herbert Schildt

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Throwing an Exception

The preceding examples have been catching exceptions generated automatically by the JVM. However, it is possible to manually throw an exception by using the throw statement. Its general form is shown here:

throw exceptOb;

Here, exceptOb must be an object of an exception class derived from Throwable.

Here is an example that illustrates the throw statement by manually throwing an ArithmeticException:

Image

Notice how the ArithmeticException was created using new in the throw statement. Remember, throw throws an object. Thus, you must create an object for it to throw. That is, you can’t just throw a type.

Rethrowing an Exception ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required