Sunday, March 13, 2011

Catching and Handling Exceptions in java using try-catch-finally

The syntax for the usage of try, catch and finally block is given below.

try{
//some java statements which can throw exception
???
}
catch(<exceptionclass1> <obj1>){
//deal with exception
}
finally{
//close open streams etc...
}


 

We have already seen the class which has to deal with the exception here.

Now that you've familiarized yourself with the ListOfNumbers class and where the exceptions can be thrown within it, you can learn how to write exception handlers to catch and handle those exceptions.
The three sections that follow cover the three components of an exception handler -- the try, catch, and finally blocks. So dealing with exceptions one by one :


 

The try Block


The first step in writing an exception handler is to enclose the statements that might throw an exception within a try block. The try block is said to govern the statements enclosed within it and defines the scope of any exception handlers (established by subsequent catch blocks) associated with it.

PrintWriter out = null;

try {
System.out.println("Entering try statement");
out = new PrintWriter(
new FileWriter("OutFile.txt"));

for (int i = 0; i < size; i++)
out.println("Value at: " + i + " = " + victor.elementAt(i));
}
The try statement governs the statements enclosed within it and defines the scope of any exception handlers associated with it.
Now if Exception is thrown, it should be handled by catch block or the finally block. So lets see next section.

 

The catch Block(s)



Next, you associate exception handlers with a try block by providing one or more catch blocks directly after the try block. You associate exception handlers with a try statement by providing one or more catch blocks directly after the try block:


try {
. . .
} catch ( ExceptionClass1 obj1. . ) {
. . .
} catch ( . . . ) {
. . .
}


The finally Block


Java's finally block provides a mechanism that allows your method to clean up after itself regardless of what happens within the try block. Use the finally block to close files or release other system resources.

Putting It All Together


The previous sections describe how to construct the try, catch, and finally code blocks for the writeList example. Now, let's walk through the code and investigate what happens during three scenarios.

No comments:

Post a Comment

Chitika