Example of try-catch-finally exception handling in java

Source: Internet
Author: User
Tags constructor exception handling finally block throw exception


This section describes how try-catch-finally statements handle errors. The example in this article is Java, but the same rule applies to C #. The only difference between exceptions in java and C # is that no exceptions have been checked in C. The checked exceptions and unchecked exceptions are described in more detail in the following sections.


Exceptions in the program indicate that some errors or exceptions have occurred. If exceptions are not handled, it makes no sense to continue the program process. A method may throw an exception for various reasons, for example, the input parameter is invalid (a negative number is input when a positive number is expected .)

Call stack
The following describes the call stack. The call stack refers to the sequence of method calls from the current method to the main method. If method A Calls Method B and Method B calls method C, the call stack is as follows:

A
B
C
After method C returns, the call stack only contains A and B. If Method B calls method D again, the call stack is as follows:

A
B
D
Understanding the call stack is very important to understanding exception propagation. From the method that throws an exception, the exception is propagated based on the call stack until a method in the call stack captures the exception. More details will be discussed later.

Throw an exception
If a method throws an exception, declare the exception in the method signature and include a throw statement in the method. The following is an example:

Public void divide (int numberToDivide, int numberToDivideBy)
Throws BadNumberException {
If (numberToDivideBy = 0 ){
Throw new BadNumberException ("Cannot divide by 0 ");
        }
Return numberToDivide/numberToDivideBy;
    }
When an exception is thrown, the method stops running at the exception. Any statement after the throw statement will not be executed. In the above example, if a BadNumberException is thrown, the "return numberToDivide/numberToDivideBy;" statement will not be executed. When an exception is caught by a catch block, the program continues to execute. Capture exceptions and explain them later.

You can throw any exception as long as the declaration is made in the method signature. You can also create your own exceptions. An Exception is a standard java class inherited from java. lang. Exception or any other built-in Exception class. If A method declaration throws exception A, the subclass exception of method throw exception A is also valid.

Capture exceptions
If one method calls another method that throws an checked exception, the method must either pass the exception or catch the exception. Catch exceptions are implemented using the try-catch block. The following is an example:

Public void callDivide (){
Try {
Int result = divide (2, 1 );
System. out. println (result );
} Catch (BadNumberException e ){
// Do something clever with the exception
System. out. println (e. getMessage ());
        }
System. out. println ("Division attempt done ");
    }
When an exception is thrown, the BadNumberException type parameter e in the catch statement represents the Exception thrown from the divide method.

If no call method or execution statement in the try statement block throws an exception, the catch statement block is ignored and not executed.

If an exception is thrown in the try statement block, for example, if an exception is thrown in the divide method, the program stream in the calling method (that is, the callDrive method) will be interrupted like the program stream in the divide method. The program stream will be restored at a catch statement block in the call stack that can catch this exception. In the preceding example, if an exception is thrown from the divide method, the "System. out. println (result);" statement will not be executed. At this time, the program will resume execution in the catch (BadNumberException e) {} Statement block.

If an uncaptured exception is thrown in the ctach block, the execution of the catch block will be interrupted as if the block throws an exception in the try statement.

After the catch statement block is executed, the program executes all the statements following the catch statement block. In the preceding example, the "System. out. println (" Division attempt done ");" statement will always be executed.

Exception propagation
You do not need to catch exceptions thrown in other methods. If you cannot do anything about the exception where the method throws an exception, you can let the method spread the exception to other methods that call the method based on the call stack. If you do this, other methods that will throw an exception must be declared in the method signature to throw this exception. The following is an example of the callDivide () method in this case:

Public void callDivide () throws BadNumberException {
Int result = divide (2, 1 );
System. out. println (result );
}
Note that the try-catch block is missing. The callDivide method will throw a BadNumberException. If an exception is thrown in the divide method, the program will still be interrupted. Therefore, if an exception is thrown in the divide method, the "System. out. println (result);" statement will not be executed. However, in this case, the program execution in the callDivide method (interrupted due to an exception thrown) will not be restored. The exception is propagated to the method that calls callDivide. The program will not be restored until a catch statement block in the call stack captures this exception. According to the call stack, the running of all methods from the method that throws an exception to the method that captures the exception will stop in the code where the exception is thrown or propagated.

IOException capture example
If an exception is thrown in the try statement block, the program's sequential execution will be interrupted, and the control flow will jump directly to the catch statement block. The code will be interrupted in several places due to exceptions:

Public void openFile (){
Try {
// Constructor may throw FileNotFoundException
FileReader reader = new FileReader ("someFile ");
Int I = 0;
While (I! =-1 ){
// Reader. read () may throw IOException
I = reader. read ();
System. out. println (char) I );
            }
Reader. close ();
System. out. println ("--- File End ---");
} Catch (FileNotFoundException e ){
// Do something clever with the exception
} Catch (IOException e ){
// Do something clever with the exception
        }
    }
If the reader. read () method call throws an IO exception, the following System. out. println (char) I); statement will not be executed. The final reader. close () and System. out. println ("-File End-"); statement will not be executed. The program directly redirects to catch (IOException e ){... } Statement block. If the new FileReader ("someFile"); constructor calls an exception, the code in the try statement block will not be executed.

Example of IOException propagation
The following code is still used as an example, but no exception is caught here:

Public void openFile () throws IOException {
FileReader reader = new FileReader ("someFile ");
Int I = 0;
While (I! =-1 ){
I = reader. read ();
System. out. println (char) I );
        }
Reader. close ();
System. out. println ("--- File End ---");
    }
If the reader. read () method throws an exception, the program stops running. The exception is propagated to the method that calls the openFile () method based on the call stack. If the call method has a try-catch block, the exception will be caught here. If this call method only throws an exception, the operation of this call method will be interrupted when the openFile () method is called, and the exception will be propagated out of the call stack. The exception is propagated out of the call stack until a method or Java Virtual Machine captures the exception.

Finally
You can also add a finally statement block after the try-catch block. No matter whether an exception is thrown in the try or catch block, the code in the finally block will always be executed. If there is a return statement in the try or catch block in the code, the code in the finally block will be executed before the return of the method. For finally examples, see:

Public void openFile (){
FileReader reader = null;
Try {
Reader = new FileReader ("someFile ");
Int I = 0;
While (I! =-1 ){
I = reader. read ();
System. out. println (char) I );
            }
} Catch (IOException e ){
// Do something clever with the exception
} Finally {
If (reader! = Null ){
Try {
Reader. close ();
} Catch (IOException e ){
// Do something clever with the exception
                }
            }
System. out. println ("--- File End ---");
        }
    }
Whether an exception is thrown in the try or catch block, the code in the finally block will be executed. This example shows that file reading is always disabled regardless of the program running in the try or catch statement block.

Note: If an exception is thrown in the finally statement block and is not captured, the finally statement block will be interrupted even if an exception is thrown in the try or catch statement block. This is why the reader. close () method in the finally statement block in the above example is also wrapped in the try-catch statement block:

} Finally {
If (reader! = Null ){
Try {
Reader. close ();
} Catch (IOException e ){
// Do something clever with the exception
                }
            }
System. out. println ("--- File End ---");
        }
In this way, the System. out. println ("-File End-"); statement will be executed forever. More accurately, this is the case when no unchecked exception is thrown. More information about checked and undetected exceptions is described in the following sections.

You do not need to catch or finally statement blocks in your program at the same time. A try block can only contain catch block or finally block. However, a try block does not have a catch block or finally block. The following code does not capture exceptions, but transmits exceptions outside the call stack. However, due to the existence of finally statement blocks, an exception is thrown, and the program can still close opened files.

Public void openFile () throws IOException {
FileReader reader = null;
Try {
Reader = new FileReader ("someFile ");
Int I = 0;
While (I! =-1 ){
I = reader. read ();
System. out. println (char) I );
            }
} Finally {
If (reader! = Null ){
Try {
Reader. close ();
} Catch (IOException e ){
// Do something clever with the exception
                }
            }
System. out. println ("--- File End ---");
        }
    }
Note that the catch block is missing.

Capture exceptions or propagation exceptions?
You may wonder: Should the exceptions thrown in the program be caught or disseminated? This depends on the specific situation. In many applications, in addition to telling users that the request operation has failed, you cannot do more on exceptions. In this case, you can capture all or most exceptions in the first method in the call stack. When an exception is propagated, you can still handle the exception (using the finally statement ). For example, if a database connection error occurs in a web application, you should close the database connection in the finally statement even if all you can do is tell the user that the operation fails. In the end, how to handle exceptions depends on whether the checked exceptions are thrown in your program or not. For more information about checked and unchecked exceptions, see the following.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.