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 ...

Get Java Garage now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.