Exception handling of Java learning

Source: Internet
Author: User

Copyright Notice: Original is not easy, reprint please specify transfer from http://blog.csdn.net/weewqrer/article/details/51913194

Abnormal recovery is the most important method to improve robustness.

Foreword: This article is my own note, basically is my translation "thinking in Java" The 12th chapter, the translation is not the goal, the purpose is wants to write once the impression is profound, because some sentence translation is not good, copied the original text ...

If someone thinks the article is mixed with English very awkward words, leave a message, then I change ...

Basic concepts

An exception condition (exceptional conditions) is an issue that can prevent a program from continuing to execute. You can't continue because you don't have enough information to handle the problem in this context, all you have to do is jump out of the current context and put the problem on the previous level. This is what happens when you throw an exception.

When throwing an exception, there are a few things that happen: first, just like creating another object, create an exception object on the heap with new, then the current execution path is terminated, the exception object's reference is ejected from the current environment, and the exception handling mechanism takes over and starts to find the right place to execute the program. The proper place is the exception handler (exception handler), whose job is to recover from the error state, so that the program either runs in a different way or continues execution.

For a simple example, the reference is not initialized:

if(t == null)    throw new NullPointerException();
    • 1
    • 2
    • 1
    • 2

The above program throws an exception, so you don't have to worry about it in your current environment and it will be handled elsewhere.

The exception mechanism allows us to treat everything as a transaction, and the exception mechanism can guard these transactions, "... In distributed computing we need the exception mechanism as the most basic guarantee, if a transaction is wrong, we can discard the whole calculation ".

We can also think of exceptions as built-in recovery (undo) systems, because (under careful use) we can have a variety of recovery points in the program, and if a part of the program fails, the exception is "restored" to a known stable point in the program.

The most important thing about an exception is that if something goes wrong with the program, the exception prevents the program from going down the path. This is a real problem in C and C + +, especially in C, where there is an error and there is no way to prevent the program from continuing along the path, so it is possible to ignore the error for a long time and get into a state of complete error.

Exceptions allow us (if there is no other means) to force the program to stop running and tell us what is wrong, or (ideally) force the program to handle the problem and return to a stable state.

parameter of the exception

There are two types of exception objects: with and without parameters, with no reference on the above already seen, with the reference to see the following example:

throw new new NullPointerException("t == null");
    • 1
    • 1

You can also throw an exception from scope (scope), throw an exception, and, simply, "return" from a function or scope (scope), regardless of where the exception is thrown, means exiting from the function or scope.

In addition, you can throw any type of throwable, which is the base class of the exception. Usually for different types of errors, the corresponding exception is thrown. The error message can be stored inside the exception object or implied by the name of the exception class. The previous layer uses these messages to determine how exceptions are handled. (Typically, the information is placed only in the type of the exception, except that it does not contain any meaningful content.) )

Catch an exception

To understand how to catch an exception, you must first understand the concept of the monitoring area (guarded region), which is a piece of code that could produce an exception and immediately follow the code that handles the exception.

Try Block

If you are inside a method and throw an exception (or you call another method in this method, which throws an exception), your method exits in the process of throwing an exception. If you do not want to exit the process of throwing an exception (throw to exit), you can set a special block in that method to catch that exception. Because in this block "try" various (possibly abnormal) method calls, it is called a try block. As follows:

try{    //code that might generate exception}
    • 1
    • 2
    • 3
    • 1
    • 2
    • 3
Exception handler Exception handlers

Of course, the exception being thrown must be handled somewhere. This place is the exception handler, and there is one for each exception you want to capture. After the exception handler immediately follows the try block, the following:

try{    //code that might generate exception}catch(Type1 id1){    //处理类型Type1的异常 }catch(Type2 id2){ //……}
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

Each catch clause is like a method that receives and receives only a special type of parameter, can be used internally by the handler (ID1, ID2), or not, because the type of the exception already gives enough information, but the identifier cannot be omitted.

When an exception is thrown, the exception mechanism searches for the first handler that matches the exception type. It then enters the catch clause execution, at which point the exception is considered to be handled. Once the catch clause ends, the discovery process for the handler ends. This is not the same as switch, and the switch statement needs to be followed by a break after each case to avoid the subsequent case clauses being executed. Note that in the inside of a try block, many different method invocations can produce the same type of exception, and you only need to provide an exception handler for this type.

termination vs. Resumption
Termination and Recovery
There are two basic models in the exception handling theory, Java supports termination models (both Java and C + + support this model), and the model assumes that errors are too serious to be restored. Another way to do this is to recover, which means that the exception handler wants to do something to correct the error and then try again the method that just happened. If you want to recover, it means that you will continue to execute the original program after handling the exception.

In Java, if you want to recover, do not throw an exception when encountering an error, but instead, call a method that can fix the error. Alternatively, place the try block in the while and try it until the result is satisfied.

Historically, programmers started using the recovery method, but eventually skipped the recovery and used the terminating model. Although the recovery is fascinating, it does not work in practice, primarily because the recovery program has to know where the exception was thrown and to deal with the thrown place. This makes the program difficult to write and also difficult to maintain because large programs have many exception-throwing points.

Exception handling of Java learning

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.