O'Reilly logo

Java Garage by Eben Hewitt

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

Catching Exceptions

In the preceding examples, all of the methods throw an exception up to the caller. But you catch exceptions to handle them in your code.

You can declare one or more catch blocks for each try block. There can be no code between the end of the try block and the beginning of the catch block.

Inside a try block, if your code generates an exception, processing stops immediately, and the runtime checks each subsequent catch block to match the exception type declared with the exception type thrown. Upon finding a match, it enters the catch block and executes whatever handling code is in there. Like this:

 void someMethod() { throw new UnknownHostException(); System.out.println("Uh-oh!"); //this line will never be printed. } catch ...

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