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
The three sections that follow cover the three components of an exception handler -- 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 atryblock. Thetryblock is said to govern the statements enclosed within it and defines the scope of any exception handlers (established by subsequentcatchblocks) associated with it.PrintWriter out = null;The
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));
}trystatement 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
tryblock by providing one or morecatchblocks directly after thetryblock. You associate exception handlers with atrystatement by providing one or morecatchblocks directly after thetryblock:try {
. . .
} catch ( ExceptionClass1 obj1. . ) {
. . .
} catch ( . . . ) {
. . .
}
The finally Block
Java'sfinallyblock provides a mechanism that allows your method to clean up after itself regardless of what happens within thetryblock. Use thefinallyblock to close files or release other system resources.
Putting It All Together
The previous sections describe how to construct thetry,catch, andfinallycode blocks for thewriteListexample. Now, let's walk through the code and investigate what happens during three scenarios.
No comments:
Post a Comment