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 atry
block. Thetry
block is said to govern the statements enclosed within it and defines the scope of any exception handlers (established by subsequentcatch
blocks) 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));
}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 morecatch
blocks directly after thetry
block. You associate exception handlers with atry
statement by providing one or morecatch
blocks directly after thetry
block:try {
. . .
} catch ( ExceptionClass1 obj1. . ) {
. . .
} catch ( . . . ) {
. . .
}
The finally
Block
Java'sfinally
block provides a mechanism that allows your method to clean up after itself regardless of what happens within thetry
block. Use thefinally
block to close files or release other system resources.
Putting It All Together
The previous sections describe how to construct thetry
,catch
, andfinally
code blocks for thewriteList
example. Now, let's walk through the code and investigate what happens during three scenarios.
No comments:
Post a Comment