End Google Ads 201810 - BS.net 01 --> e1087. try/catch Statement


The try/catch statement encloses some code and is used to handle errors and exceptions that might occur in that code. Here is the general syntax of the try/catch statement:

كود:
try {
        body-code
    } catch (exception-classname variable-name) {
        handler-code
    }
The try/catch statement has four parts. The body-code contains code that might throw the exception that we want to handle. The exception-classname is the class name of the exception we want to handle. The variable-name specifies a name for a variable that will hold the exception object if the exception occurs. Finally, the handler-code contains the code to execute if the exception occurs. After the handler-code executes, execution of the thread continues after the try/catch statement. Here is an example of code that tries to create a file in a non-existent directory which results in an IOException.

كود:
String filename = "/nosuchdir/myfilename";
    try {
        // Create the file
        new File(filename).createNewFile();
    } catch (IOException e) {
        // Print out the exception that occurred
        System.out.println("Unable to create "+filename+": "+e.getMessage());
    }
    // Execution continues here after the IOException handler is executed
Here's the output: Unable to create /nosuchdir/myfilename: The system cannot find the path specified