View RSS Feed

Java Exception

Catching an Exception

Rate this Entry
by , 11-29-2011 at 03:07 AM (807 Views)
Following on from our previous tip on exceptions, in this tip we will look at catching an exception. One of the key concepts to understand is the concept of a guarded region. It is a section of code that might produce exceptions and is followed by the code to handle a particular exception. They are often grouped into all the possible exceptions for a particular method or piece of code.

The try block
The first part of the region is the try block. This is when you’re inside a method and you throw an exception or if another method is called and throws an exception, the method will then exit in the process of throwing the occurring exception.
Java Code:
try {
// Code that might generate exceptions

When you are catching and handling exceptions, you put everything in a try block and capture all the exceptions in one place. This means your code is much easier to write and read because the goal of the code is not confused with the error checking.
Exception handlers
Once the exception is thrown, you setup blocks of code to handle the different type of exceptions that can take place in your code. This block is called an exception handler. You setup one for every exception type you want to catch. Exception handlers immediately follow the try block and are denoted by the keyword catch:
Java Code:
try {
} catch(Exception1 ex1)|{ 
	// Handle exceptions of Type1
catch(Exception2 ex2) { 
	// Handle exceptions of Type2
} catch(Exception3 ex3) {
	// Handle exceptions of Type3 // etc...
Termination vs. resumption
There are two basic models in exception-handling theory. Java supports termination, in which you you decide that the error is too critical to continue. The alternative is called resumption. In this case, the exception handler is does something to rectify the situation, and then the method is retried, presuming success the second time. If you want resumption, it means you still hope to continue execution after the exception is handled. Resumption code is difficult to write and maintain since you need to be aware of where the exception is thrown and handle the exception in a very precise manner.

Submit "Catching an Exception" to Facebook Submit "Catching an Exception" to Digg Submit "Catching an Exception" to Submit "Catching an Exception" to StumbleUpon Submit "Catching an Exception" to Google