try Statements


try Statements

There are two ways to handle Java exceptions ”you can handle an exception where it occurs using a try statement or you can throw the exception to another section of code and handle it there. With a try statement, the code that can throw the exception is placed inside a block of code after the try keyword. One or more catch clauses can be used to catch any thrown exceptions. The finally clause is for code that will run regardless of whether an exception is thrown or caught.

The general syntax of the try statement is ”

 try {    //  code that can throw an exception } catch {exception_type exception_name) {    //  code to handle the exception } finally {    //  code that will always be run } 

Every checked exception must ultimately be sent to a catch clause. Unchecked exceptions can be tested for and processed inside a try statement as well. You can write nested try statements.

Let's look at the different parts of the try statement in more detail.

The try Statement

A try statement is defined using the try keyword. Code that can generate an exception is placed inside a block of code after the try statement ”

 try {    //  code that can throw an exception } 

The block of code after a try statement acts like any other inner block of code. Any local variables declared inside the block of code will not be available outside of it. If an exception is thrown, the block of code exits. Any code following the point where the exception occurs is not executed. The system will then try to match the exception type with any catch clauses. A try statement must be followed by either one or more catch clauses or a finally clause.

The catch Clause

A catch clause catches and processes an exception of a specified type. A catch clause is defined by the catch keyword, an exception type and exception variable name in parentheses, followed by a block of code ”

 catch (exception_type exception_name) {     //  code to handle the exception } 

When an exception is thrown inside a try statement, the system will try to match the exception type against the types declared in any subsequent catch clauses. If a match is found, the block of code following the catch clause is executed. A superclass of the exception that is thrown is considered a match. For example, if a catch clause declares an exception of type Exception (the parent class of all catchable exceptions), the catch clause will catch all exceptions that can be generated.

There can be multiple catch clauses associated with a given try statement. Multiple catch clauses are useful if a section of code can generate more than one type of exception. If multiple catch clauses are used, only one of them will be called when an exception is thrown. You must place exception subclasses before superclasses in the catch clause sequence. For example, if you place an IOException catch clause before a FileNotFoundException catch clause, the IOException catch clause will be called if a FileNotFoundException exception occurs (because FileNotFoundException is a subclass of IOException ). The FileNotFoundException catch clause will never be called. You can have zero catch clauses if you define a finally clause.

A catch clause will typically provide a detailed error message and/or try to correct the problem. You can provide a short description of the exception by concatenating the exception object onto a String . For example, the following code would concatenate a String representation of an IOException object with the string "exception type: "

 catch (IOException ioe) {    System.out.println("exception type: " + ioe); } 

The finally Clause

A finally clause can be optionally placed at the end of a try statement. However, if a try statement does not have one or more catch clauses following it, it must be followed by a finally clause. A finally clause consists of the finally keyword followed by a block of code:

 finally {    //  code that will always be run } 

The block of code after a finally clause will be executed whether or not an exception is thrown and whether or not a thrown exception is caught. A finally clause can be used to return data or to ensure that things such as closing I/O streams occur even if an exception is thrown.

Example: Using try statements

A lot of things can go wrong during I/O operations. You can try to read a file that doesn't exist, you can attempt to read past the end of a file, or a system interruption may occur during your read or write operation. Because of their tendency to throw exceptions, I/O operations are often placed in try statements.

The TryDemo class attempts to read the first line of a user -specified file and assign this text to a String . Inside a block of code following the try statement the user is prompted for a file name and a BufferedReader object is created according to the specified file name. Two catch clauses are provided. The first catches a FileNotFoundException that occurs if the specified file is not available. The second responds to any other IOException that might occur during the read or file open operations. A finally clause returns either the text that was read from the file or a default String .

 import java.io.*; public class TryDemo {   public static void main(String args[]) {     String fileName;     String text = "bailey boy";     //  Create two BufferedReader objects.     //  The first reads keyboard input.     BufferedReader reader =         new BufferedReader(             new InputStreamReader(System.in));     //  The second BufferedReader will read data     //  from a file.     BufferedReader fileReader;     //  The user is prompted for a file name     System.out.print("Enter file name:  ");     //  The program reads the keyboard input and     //  attempts to open and read the specified file.     //  These operations can throw an IOException and a     //  FileNotFoundException and are placed in a try     //  statement.     try {       fileName = reader.readLine();       fileReader =         new BufferedReader(new FileReader(fileName));     //  The first line of the file is read and assigned     //  to the text variable       text = fileReader.readLine();     }     // This clause catches a FileNotFoundException.     catch (FileNotFoundException fnfe) {       System.out.println("File not found. "+                          "Default text used\n");     }     // This clause catches a generic IOException from     // the input read, file open, or file read     // operations     catch (IOException ioe) {       System.out.println("IO exception occurred");     }     //  The finally clause prints either the text read     //  from the file or the default text.     finally {       System.out.println("\n"+text);     }   } } 

Output ”

The output will differ , depending on whether or not you enter a valid text file name. If you enter a valid file name, the first line of that file will be written to the console. If you don't enter a valid file name, the text "bailey boy," the author's dog's nickname, will appear on your screen.



Technical Java. Applications for Science and Engineering
Technical Java: Applications for Science and Engineering
ISBN: 0131018159
EAN: 2147483647
Year: 2003
Pages: 281
Authors: Grant Palmer

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net