Java Exception Handling Mechanism

Source: Internet
Author: User

We all know that the Java Exception Handling Mechanism isProgramPersonnel is very important because with this mechanism, we do not need to, as before, when an exception occurs, we can only watch our program stop working, or exceptions may occur in every sentence.CodeSo that our code becomes increasingly difficult to read. Because of this, in the past, many programmers have chosen to ignore the possible exceptions and handed over the handling process to the user programmers. I have done my job anyway, as to whether the program will generate exceptions, you can do it yourself. Even if exceptions occur, you can handle them yourself. Because of this attitude, there are some ugly code collections left behind! But we can't blame these people too much, because they are also victims. Anyone who wants to write a lot of code just to prevent exceptions that may or may not occur! Even if it is a programmer, No, it is because it is a programmer that they want to be more lazy!

This is because we want to be lazy programmers, so there will be a convenient exception handling mechanism. The next step is to introduce how much convenience the exception handling mechanism can bring to us.

So what is an exception? The so-called exception is the problem that occurs in the program to prevent the current method or scope from continuing to execute. Therefore, without an exception handling mechanism, our program will only crash and cannot be executed. So how can we establish an exception handling mechanism? To establish an exception handling mechanism, you must first understand the principles of the exception handling mechanism. How does the exception handling mechanism work? It's actually very easy. What would you do if you had a bomb that was about to explode? Most people share the same answer, that is, they will immediately lose it! Yes, that is, discard. The exception handling mechanism is the same as that of the average person. Select to throw this exception to the execution point of the current method. So the question is, where does it throw an exception? It is the place where exceptions are handled. Here, we need to note that the exception is caught by the exception handling mechanism. Why? This problem is the core of the exception handling mechanism. If you understand it, you can understand why the exception handling mechanism is like this. First, the exception handling mechanism will use new to create an exception object on the stack, and then the current execution path is terminated, and the reference to the exception object is displayed from the current environment. Yes, it is to pass the reference of this exception object to the next exception handler. This is like a method call. In fact, this is also the case. Since an exception object will be created, what about the destruction of this object? Anyone who has used Java a little knows that there is no need to worry about this problem, because there is a garbage collector. Since the exception object is created on the stack, the garbage collector knows when to recycle it, and it will always be recycled (although I don't know when to recycle it ). After understanding the principles of the exception handling mechanism, let's see how the exception handling mechanism is established? The general code for establishing an exception handling mechanism is as follows:

 
Try{....}Catch(Exception e) {e. printstacktrace ();}

 

When we see the above Code, we need to know two points: What are the processing differences between try and catch? First, the code in try is the place where exceptions may occur, while the catch parameter is the exception type, and the exception processing is involved. With this code, we can capture exceptions and "correctly" handle exceptions. Yes, this is indeed a quotation mark, because most exceptions can be correctly handled, however, for some exceptions, we don't even know what the connection type is, so there is no correct solution at all. However, please rest assured that in most cases, this kind of processing is more appropriate. Even if we cannot handle exceptions, we can still output stack information as I wrote above, at least, our code can run below without interruption.

Java's Standard Library provides a large number of exception types, such as our common nullpointer, but sometimes we need to customize exceptions, as we mentioned earlier, some exceptions cannot be exactly known, so we need to customize the exception and handle it. How can I customize exceptions? Just like inheritance, an exception also has a base class, that is, exception, which can capture all exceptions, therefore, as long as our custom exceptions inherit from this base class, they can be captured by the exception handling mechanism, for example:

 
ClassMyexceptionExtendsException {}

Of course, you can also inherit more detailed exception types, but this is generally enough, as long as our custom exceptions can be caught by the exception handling mechanism.

When it comes to the exception class, we must remind you that if your exception handling mechanism involves exception handling and other exceptions inherited from it (all exceptions are inherited from it), then, your exception must be put at the end, because the Exception Handling Mechanism has a so-called exception matching problem. It will find the exception that matches it recently and then enter the relevant processing. Therefore, exception is placed at the end. Otherwise, other specific exceptions are blocked. This applies to the derived exception class and its base class, and the derived exception class can also be captured by the processing program of the base class.

Of course, since there are exceptions, especially program development, there will always be so-called exception logs, just like android logs, so that we can easily view the exception generation process in the program. So how to record exceptions to logs? Let's take a look at the relevant code:

  class  loggingexception  extends   exception {  private   static  logger = logger. getlogger ("loggingexception" );   Public   loggingexception () {stringwriter trace  =  New   stringwriter (); printstacktrace (  New   printwriter (TRACE); logger. severe (trace. tostring () ;}} 

Let's take a look at this code. Why is logger static? We all know that the so-called static data can be directly used without creating an object. Just like the constructor below, the severe () method on logger will be called directly. If you still need to create an object in the constructor, it's a joke !! Okay, let's take a look at this logger object. There are a lot of things to talk about the logger object, but to be honest, there is really no need for it, because I can't make it clear about those things, and I don't need to know much about them, just know, this logger will send the exception information, that is, the string output after it is sent to system. err. As for what system. Err is, I don't have to talk about it. Just check it. Note the severe () method. This method will record a severe message, and the so-called severe message is the message we usually see in the log (well, this one is really bad, this is because I am a little unfamiliar with this aspect. I will tell you after I get familiar with it. If there is any error here, please let me know) previously, I only talked about how to write the exception information into the log, but how can we make it visible? This is generally in the exception handling program, the following code:

 Public   Class  Loggingexception {  Private   Static Logger logger = logger. getlogger ("loggingexception" ); Static   Void  Logexception (exception e) {stringwriter trace = New  Stringwriter (); E. printstacktrace (  New  Printwriter (TRACE); logger. Severe (trace. tostring ());}}  Public   Static   Void  Main (string [] ARGs ){  Try  {  Throw  New  Nullpointerexception ();}  Catch  (Nullpointerexception e) {logexception (e );}} 

It is easy to understand here. We throw an exception in the code, capture the exception, and output the information to the log. This can also be used to capture and record exceptions written by others.

The previous content has already completed the basic content of the exception handling mechanism. Yes, there is not much to talk about in this part, that is, we need to remember a routine. So, does it indicate myArticleIs it over? The answer is definitely not! According to my habits, when I come into contact with something, I will definitely want to know what it is, how it is used, and what problems will occur when it is used, how to solve and so on many additional sub-problems, of course, exceptions are no exception here. Let's talk about a special type of exception, runtimeexception.

Why is it special? This exception can be ignored! Yes, you are not mistaken, that is, ignore. This is of course very strange. Why can we ignore exceptions? As mentioned above, exceptions must be handled. Otherwise, the program will not be able to continue. What should we do if we ignore exceptions? Don't worry. This is because this exception is different from other exceptions. This exception shows that programming errors occur in our code. What is a programming error? There are two common cases:

1. unexpected errors, such as null references passed out of the control range, cannot be handled at all, because you do not know that such errors will occur, it happened by accident because it was introduced when you wrote the code;

2. errors that should be checked in code, such as array out-of-bounds issues. This problem is really caused by your own negligence. Why are our designers responsible for your mental disability?

Therefore, runtimeexception can be ignored because it is a problem of your own programming, and you must be responsible for it.

The next step is about the finally clause. The finally clause is very common in try-catch blocks because it can help us with some things, such as cleaning. Yes, because the finally clause can be executed regardless of whether an exception in the try block is thrown, even if you use return in the try block .. Sometimes it is difficult for us to properly close our resources. For example:

Try{Inputfile in=NewInputfile (...);}Catch(Exception e ){...}

How do you turn off your resources? If you add this sentence at the end of the try block: In. close (), so when an exception occurs, your code will be detached from the try block, so closing this action will not happen! Therefore, you need to use the finally clause, for example:

 
Try{Inputfile in=NewInputfile (...);}Catch(Exception e ){...}Finally{In. Close ();}

In this way, we can ensure that the resource is properly closed no matter whether the try block throws an exception.
However, this causes many problems. In some cases, the code in the finally clause will also generate exceptions. In this case, the exception thrown in the finally clause will replace the original exception, causing us to lose the exception. Also, if return is used in the finally clause, it is actually return, because it will certainly be executed. The loss of exception information is a hidden problem in the exception handling mechanism. Some programmers even do not find this problem at all. This is what I will talk about next, but now, let's continue with the problem above.

For the first case above (the second case, you only need to return without it), our solution is to use nested try, in the finally clause, try-catch is used to capture and handle exceptions. Nested try-catch is useful. For example, an exception occurs when an object is created. What should I do at this time? For example:

  try  { inputfile in  =  New   inputfile (...);   try   {...}   catch   (exception E) {...}   finally   {In. close () ;}  catch   (exception e ){...}  

No. If there is a problem with the in build, the related exception handling will take over, and the finally clause will be used to close the resource correctly.
Next, we will discuss the problem of exception loss. In Java, as long as this Code may throw an exception, it will force you to use the exception handling mechanism, but sometimes we have never thought about how to handle the exception! The correct Exception Handling Mechanism should be used when you know how to handle exceptions, but Java has set it as mandatory. In this case, the problem occurs. I don't know how to handle the exception. When my code must be compiled again, I can only compile an incorrect processing program, after my code has been compiled, it is very likely that I have forgotten this exception because there is no prompt! Then, the exception that should have been handled immediately will remain in my code forever, but I will never know. Therefore, in this case, we usually choose to print stack information for processing, so that we can solve the problem later. Or another common practice is to pass exceptions to the console. For example:

 
Public Static VoidMain (string [] ARGs)ThrowException {...}

In this way, we do not need to use try-catch in main (). During the running of our program, we will see the relevant exception information printed in the console, we don't have to worry that we will lose exceptions. However, this problem is not common, because it is obviously not enough to process the input/output of a file, because it is really complicated !!!
So we have other methods to avoid this problem, namely exception chain. For example:

 
Try{....}Catch(Exception e ){Throw NewRuntimeexception (E );}

The exception chain must be described here. When we add an exception as a parameter after the exception, it is a parameter of the constructor of the exception, it will be like a linked list, put the exception as a parameter after this exception. This is to ensure that we will not lose any original exception information, because they will eventually be displayed together. However, only three types of exceptions have their own exception chain functions, namely error, exception, and runtimeexception. For other exceptions, you must use the initcause () method. In this way, we do not need to write a try-Catch Block or exception description. we ignore the exception and let them come out of the Call Stack. In addition, we can also use getcause () capture and handle specific exceptions. However, remember that the exception to be carried must be processed at the end of the process. The reason is that the exception of the base class is the same as that of the derived class. Of course, we can also create a child class of runtimeexception, which has a higher degree of freedom.

When exceptions are used, there are also some restrictions. For example, when overwriting a method, we can only throw the exception listed in the exception description in the base class method. Why? This is because the code used by the base class can work the same way when applied to the object of its derived class. If the derived class does not have an exception description, obviously, this method cannot work normally, and when the derived class is transformed upwards to the base class, the exception indicates that it has not followed the upward transformation, so there will also be problems. Also, when a class implements both an interface and inherits a base class, the exception is indicated by the base class, and the same principle is also true. However, the exception restriction does not work for the constructor. The constructor of the derived class can throw any exception, the exception description of the constructor of the derived class must contain the exception description of the base class constructor, because the base class constructor is always called, such as the automatic call of the default constructor. However, the derived class constructor cannot catch the exception thrown by the base class constructor. This refers to the exception we throw when calling the base class constructor. What should I do? You can only use try-catch blocks.

The method of the derived class does not throw any exception, because even if the method of the base class throws an exception, the existing program is not destroyed, because the base class method itself has been overwritten! The exception of the base class does not affect the use of the method of this derived class, just like the children and parents who have already been separated, basically, the parents do not affect the children's home. Therefore, the inheritance of exceptions is smaller than that of interfaces, rather than larger.

Here, let's talk about why the main thread cannot catch the exceptions thrown by the added thread because the added thread itself also has a related exception handling mechanism, even if it does not, but it will also be displayed in the console, so the main thread cannot be captured. So how do we add an exception processor to every thread? We can modify the executor production method and append an exception processor to each thread object. Therefore, we must first implement a thread. uncaughtexceptionhandler interface, such:

 
ClassAImplementsThread. uncaughtexceptionhandler {Public VoidUncaughtexception (thread t, throwable e ){...}}

Then, append the exception processor to the thread object, for example, thread t = new thread (runnableclass); T. setuncaughtexceptionhandler (new ()). yes, we can indeed set the exception processors for each thread one by one based on the situation, but we are more concerned that our exception processors are actually the same, so, we can set a static domain in our Thread class and set this processor as the default, for example, thread. setuncaughtexceptionhandler (new A (); this is called only when the thread does not have a proprietary exception processor. In general, our compiler is doing this: it shows whether each thread has a dedicated exception processor. If not, let's look at this thread class (thread group) whether the thread group exclusive (that is, to check whether these threads are placed in one block). If it still does not exist, call the system default.

We often see this sentence: "exceptions go directly to main () without being captured ." What does this sentence mean? For example:

  void   F () {  try   {...}   catch   (exception E) {...}}   void   G () {  try  {f ();}   catch   (exception E) {...}}   Public   static   void   main (string [] ARGs) {G () ;} 

Let's take a look at it. In Main (), calling g () and g () calls F (). If the exception in F () is not handled, then it will run to G () and g () without handling this exception, and then it will run to main (). This is the process to be expressed in this sentence.
Finally, I will list the usage of exceptions as the end of this article. I hope this article will help those who want to know about exceptions:

1. Handle the problem at the appropriate level (capture exceptions only when you know how to handle them );

2. Solve the Problem and call the method that generates an exception again;

3. Perform a Minor fix, and then continue to execute the patch in the case of exceptions;

4. Use other data for calculation, instead of the expected value returned by the method;

5. Try to finish what can be done in the current running environment, and then re-deliver the same exception to a higher level;

6. Try to finish what can be done in the current running environment, and then throw different exceptions to a higher level;

7. Terminate the program;

8. Simplify it. If your exception mode is too complicated;

9. Make the class libraries and programs more secure.

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.