Java Exception handling mechanism

Source: Internet
Author: User
Tags throw exception try catch

=============================================

original link: Java exception handling mechanism reproduced please specify the source!

=============================================

A high-quality system not only takes into account the completeness of its functions, but also the correctness, robustness, reliability, ease of use, readability (understandable), extensibility, reusability, compatibility, portability ... And when it comes to the "robustness" in this area, we have to mention Java's exception system.

In the development process see a number of unreasonable use of exception, such as:
try{} contains too many code;
The exception type is not subdivided by catch (excrption e);
The catch exception is not processed;
Use exception to control the code flow (the issue is controversial);
When designing an interface, always add a throws Exception in the back ...
Such code may be able to make the program run normally, in the program can not be said to be errors, can only be defined as the use of unreasonable. But for a high-quality system, there is no doubt that such code belongs to inferior code!
In the development process, when the parameters are received in a method, the next thing to do is to verify the parameters, verify the type of the parameters, the range of values and so on whether the input requirements are met. So if the checksum fails, how do you handle it? is the direct return null? or set a default value for the parameter? Or directly throws throws an exception?
If an exception is thrown, is the exception to be thrown or a run exception thrown? If you throw a run exception, how do you choose the type that throws the exception? To understand these problems, you need to understand the Java exception system.
All of the extensible structures in Java can be divided into two types according to type:
Error: Virtual machine error, the occurrence of this kind of error is generally more serious, the program can not capture and do not need to be processed. There is only one result of this error-the thread exits, and if the thread is the main thread, the program ends. If this error occurs, you need to find the trigger point and optimize the program. For example: Virtualmachineerror,ioerror.
Exception: All exception can be captured, but depending on whether a forced capture is required, it can be divided intoexception to be inspected (forced capture/throw)AndRun-time exception (no enforcement required)
The run-time exception is mainly runtimeexception and its subclasses, except for those that are being inspected for exceptions.
A checked exception cannot be compiled if it is not captured or thrown.

For error, we don't have to pay too much attention, the error is not a problem in the program, not under the control of the developer. So there is no discussion here.
For exception, we need to understand the following questions:
1. Where did exception come from?
2, how to deal with the captured exception?
3, how to throw exception?
about the first question: Where did exception come from?
a) The bottom is thrown up.
When calling a method, some methods throw checkedexception, which needs to be forced to be processed, either by a try catch or by continuing the throw.
b) unsolicited in the party.
When the method in the execution of the process found that the normal execution conditions are not met, then you can choose to actively new a exception to throw.
For example, when a parameter is checked for NULL, you can actively throw a nullpointexception, or you can actively throw illegalargumentexception if the parameter range does not meet the requirements.
about the second question: How to deal with captured exception?
Most of the captured exception are checkedexception that are thrown at the bottom because there is no need to capture it for unchecketexception, even if it is captured and cannot be processed
So what do we do with capturing the checkedexception?
The exception is judged, and if it can be handled in this method, it is handled in this method. If it cannot be handled in this method, it is thrown according to the throw policy
Do not need to be thrown: Modify the database commit transaction and, if an exception occurs, a transaction rollback in the catch. This is the case that the transaction can be transacted in this method without the need to throw up.
And this method can not be processed, you need to throw an exception, then how to throw it? Is it thrown unchecketexception or checketexception?
about the third question: How to throw a exception?    What is the throw strategy?
Here is the difficulty of the problem, how to define this throw strategy?
Programmers have a common problem, always like to find a universal rule, any question according to the criteria can find a solution. There are many questions that are not explicitly answered, resulting in a surefire plan not found in the throw strategy.
The main contradiction of throwing strategy is: When this method can not handle the exception need to throw, is thrown unchecketexception or checketexception?
Personally, I think, first judge whether there is a way to deal with, if there is a way to handle the throw checkedexception, if there is no way to deal with the exception, then directly throw uncheckedexception. There are still subjective questions: how can you tell if the upper layer is able to solve the anomaly?
For example:

      PublicFileInputStream (File file)throwsFileNotFoundException {...if(FilePath = =NULL) {            Throw NewNullPointerException ();//the file path is null to throw uncheckedexception}Else if(File.isinvalid ()) {Throw NewFileNotFoundException ("Invalid file path");//throw checkeexception If file not found        }        ....     }


In this method, the use of the above throw strategy is not appropriate, because there is no way to prove that the call can solve the filenotfoundexception and not solve the nullpointerexception ...
Find the answer on the Internet when the occasional see a post on the issue, only to find that the original 14 years ago, there has been a group of people heated discussion of this issue, and from 2003 Monday to the discussion to 2007, lasted four years, and finally closed to discuss the end. Post Link: Why use Checked Exceptions in Java
The discussion in the post of the unusually fierce, views, can be called the schools of contention! There is a truth in every opinion, but in the end there seems to be no answer, but there is a person's opinion in it that is quite agreeable:so exceptions that cannot be handled are thrown using uncheckedexception, and do not expend effort to design how to throw
He gave some ideas to support the conclusion: "Tianya" argument, here is not tangled here, I believe that every serious thinking about the problem will have their own views.
There's an idea here, is it something wrong with our attention?the difference between the performance of Uncheckedexception and checkedexception is whether they are checked by the compilation mechanism, and if they want to be detected by a compile mechanism, use checkedexception. Otherwise, use Uncheckedexception. Other wordsIf you needthe caller pays attention to the exception, then uses checkedexception to force the caller to pay attention and handle it, if the caller does not need attention, then make uncheckedexception.
If that were the case, the problem would be clear,in the implementation of the method, for the bottom of the checkedexception, if you can solve the capture solution, if not solve the direct throws continue to throw. For an unsolicited exception, throws a checkedexception if it is necessary for the caller's attention and handling, and throws uncheckedexception if it is not required. and whether the caller needs to focus on the exception, there is the implementation of this method to decide, no need to consider the other. This throw strategy is still possible!
On the other, in "effective Java" in the exception of the author put forward a point of view: 1,try to keep the failure atomic。 If an exception occurs during execution, before exiting, you should restore the data modified before the exception occurs to avoid data errors!!! This problem is still more serious, it deserves the attention of the key.

---END---

Java Exception handling mechanism

Related Article

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.