A brief analysis of Java anomaly System

Source: Internet
Author: User

Recently read the "Java programming thought" in the book to see the description of the anomaly, combined with their own reading source experience, to talk about their own understanding of the anomaly. First remember the following two words:

  Unless you can solve the exception, do not capture it, if you intend to log the error message, then do not forget to throw it again.

  An exception represents an error and can represent a message.

First, why there are anomalies

This problem is not difficult to understand, if everything is done according to our design, then the general (not the general situation is that we design is flawed) is not abnormal, such as a division operation:

 Public int div (int x,int  y) {  return x/y;}

Of course we designed the divisor can not be 0, we also added a comment on the method name, the output can not be 0, if the user according to our request to use this method, of course, there will not be an exception. However, many times, users do not necessarily read our comments, or the input data is not user-specified, but the program calculates the intermediate results, this time will result in the case of a divisor of 0.

Now abnormal situation appeared, the program should do, the direct hanging off is certainly not, but the program really can not handle this kind of unexpected situation, so we have to find a way to tell the user, so that the user to decide, that is, the program needs to be encountered this abnormal situation packaging sent out, It is up to the user to decide how to handle.

  an exception represents a message . Programmers familiar with Eofexception will generally understand that this exception, indicating that the content of the information is greater than the representation of an exception, unfamiliar to the reference to my previous blog: http://www.cnblogs.com/yiwangzhibujian/p/7107084.html. When exceptions in this scenario, including most of the user-defined exceptions, fall into this category, there is no need to resolve them.

Ii. Classification of Java exceptions

Before continuing with the following section, it is necessary to understand the Java exception classification, through the Java API can see the following inheritance relationship:

A Brief introduction:

    • Throwable is the parent class for all exceptions
    • Error indicates that a serious problem has occurred, can be captured but not captured, because the capture is not resolved, this is not produced by the program, the bottom of the problem let him hang it up.
Third, the understanding of abnormal handling

Repeat the first sentence, unless you can solve the exception, do not capture it, if you intend to log the error message, then don't forget to throw it out again . But seriously, since the emergence of an exception, the basic can not be solved, because our program can not go backwards to the occurrence of abnormal code, but also not in the same input (cannot change the input, otherwise the result is what use), the same code (can not dynamically change the original code) situation to let it no longer abnormal, Otherwise the same piece of code, in the case of the same input has two different results, who dares to use it?

Unless our program relies on external conditions, and exceptions caused by external conditions, we can change the external conditions to satisfy the program requirements, but this is basically detected before the program executes.

3.1 How to solve the exception

To give two simple examples to facilitate understanding, the first one is about the socket, the specific socket knowledge can refer to my previous blog: http://www.cnblogs.com/yiwangzhibujian/p/7107785.html.

3.1.1 Repeated attempts to solve occasional problems

After the socket is connected, we can send a message through the socket, the efficient way to use the socket is to establish a connection to continue to be used, but in this case, there is a need to pay attention to the question, that is, every time I send a message, I want to check whether the socket is still in the connection , which I have described in the above blog, does not need. The pseudo code is as follows:

// There is a connection in the socket Socket socket= ... // the data to be sent String data= ""; Try {    socket.write (data);} Catch (excetption e) {    // print the log and re-connect the socket    socket=new  socket ( Host,port);    Socket.write (data);}

As you can see, if the current connection is unavailable (for a long time without being actively disconnected by the server, or if the network jitter is causing the disconnection), then we catch this exception and then reestablish a connection to send. This is the most basic solution, a bit more advanced is to set a repetition, when the exception occurs when the specified number of repeated.

If we think about this connection exception we do not really solve it, but through a new connection to deal with, we solve the problem is not the exception, but the sending of data problems, we solve the problem of sending data is not successful.

Similarly, repeated attempts to solve the occasional problem, this occasional is also the external conditions caused by the occasional, rather than the program itself problem.

3.1.2 don't want to see the error stack

The general web three-tier architecture, Action,server,dao, if the exception is not satisfied with the above conditions, if the exception is not caught, then the user will see a 500 page, with the stack information, this kind of thing is not a friendly way of expression, in this case, We need to wrap the method in the action layer with one of the largest try catch and jump to the error page when an exception occurs.

 Public string Method (string param) {  try  {    // logical handle  catch (Exception e) {    e.printstacktrace ();     // Jump to error page   }}

In fact, we did not solve the exception, we just solved the problem caused by the exception, the exception itself is still there, the real solution is the programmer to solve the bug and then back online.

This is also an alternative solution, forced to do so, in fact, the exception is swallowed, swallowed a little bit of information left.

3.2 What should we do?

The first condition or the sentence, if not to solve the abnormal situation, then do not capture it, not to swallow him.

Of course there are times when you're going to log the unusual logs, but at the beginning, the exception also represents a message, just like the indexoutofboundsexception, IOException itself name can already indicate the most information of the exception, That is to say, the exception stack is basically able to get information about the exception part, but some of the exception stack does not have, that is, the external information when the exception condition occurs.

Of course, when throwing an exception, the virtual machine itself will print as much as possible the input that causes the exception, but when we want to get additional environmental information , we need to catch the exception and print it out.

Just like the simple exception of 0, and the string to the number exception, the exception stack itself will provide basic information, but if we in a user interaction environment, if we want to know which user's input caused the exception, this time the system generated by the exception stack information can not meet our requirements, And this information is in a field in the current class, and we're going to take the initiative to capture and print out what we want.

Iv. Handling of anomalies

Now, here are some examples of how exceptions are handled.

4.1 For exceptions that are not necessarily seen

Suppose you write a tool class that is used for UTF-8 conversions of strings and byte arrays, assuming the following:

 PackageYiwangzhibujian.util;Importjava.io.UnsupportedEncodingException; Public classUtils { Public StaticString UTF8 (byte[] bytes)throwsunsupportedencodingexception{return NewString (Bytes, "UTF-8"); }     Public Static byte[] UTF8 (String str)throwsunsupportedencodingexception{returnStr.getbytes ("UTF-8"); }}

Then the person who uses your tool class will have a headache, obviously will not have the wrong, either throws this exception, either catches, actually the user cannot solve this anomaly at all.

So some people may do this, he thought since this anomaly must not appear (in essence, the JVM must be able to parse the UTF-8 code, if it can not parse the JVM will not need to continue to run), then I swallowed it, do nothing:

 PackageYiwangzhibujian.util;Importjava.io.UnsupportedEncodingException; Public classUtils { Public StaticString UTF8 (byte[] bytes) {    Try {      return NewString (Bytes, "UTF-8"); } Catch(Unsupportedencodingexception e) {}return NULL; }     Public Static byte[] UTF8 (String str) {Try {      returnStr.getbytes ("UTF-8"); } Catch(unsupportedencodingexception e) {e.printstacktrace (); }    return NULL; }}

There are people who do this, but there are two kinds of people who do it, one is to do nothing in the catch, and the other is to print out the exception in the catch, which I prefer in the latter case, because the following conditions are considered.

You think the JVM must be able to parse UTF-8, I do not object, but you can guarantee that you do not misspelled UTF-8, if you write UFO-8 it?

 Public Static String UTF8 (byte[] bytes) {  try  {    returnnew String ( Bytes, "UFO-8");   Catch (unsupportedencodingexception e) {  }  returnnull;}

Then calling your method not only has no error prompt, but also results in the return of the wrong result, resulting in a series of problems, the most deadly of which is that we do not know where the root of the error is.

Give an example of an object clone.

 PackageYiwangzhibujian.util; Public classClonetest { Public Static voidMain (string[] args) {Dog D1=NewDog ("Zhuzhuxia", 26); Dog D2=d1.clone ();//here either catch or throwSystem.out.println (D1);  System.out.println (D2); }}classdog{ PublicString name;  Public intAge ;  PublicDog (String name,intAge ) {    Super();  This. Name =name;  This. Age =Age ; } @OverrideprotectedObject Clone ()throwsclonenotsupportedexception {return Super. Clone (); }}

You can see the user call your object's cloning method is not very painful, since you provide me with cloning method, you must be able to use, if not, then take it back to rewrite it, I will not wipe your butt. So that's what we're going to do:

 PackageYiwangzhibujian.util; Public classClonetest { Public Static voidMain (string[] args) {Dog D1=NewDog ("Zhuzhuxia", 26); Dog D2=d1.clone ();//here either catch or throwSystem.out.println (D1);  System.out.println (D2); }}classdog{ PublicString name;  Public intAge ;  PublicDog (String name,intAge ) {    Super();  This. Name =name;  This. Age =Age ; } @OverrideprotectedDog Clone () {Try {      return(DOG)Super. Clone (); } Catch(Exception e) {e.printstacktrace ();//Do not save}return NULL; }}

If you run the above code, it throws an exception, because our class does not implement the Cloneable interface.

Java.lang.CloneNotSupportedException:yiwangzhibujian.util.Dog at    java.lang.Object.clone (Native Method) At    Yiwangzhibujian.util.Dog.clone (clonetest.java:+) at    Yiwangzhibujian.util.CloneTest.main ( Clonetest.java:6) [email protected]null

So, I can assume that this is not going to be an exception, but we can't guarantee that we don't make the most basic mistakes, so the stack of errors can't be saved.

Let's take a look at the HashMap in Jdk8 about cloning:

@SuppressWarnings ("Unchecked") @Override PublicObject Clone () {HashMap<K,V>result; Try{result= (hashmap<k,v>)Super. Clone (); } Catch(clonenotsupportedexception e) {//This shouldn ' t happen, since we is cloneable        Throw NewInternalerror (e);    } result.reinitialize (); Result.putmapentries ( This,false); returnresult;}

Does not run abnormally, it also did a more advanced thing, that is I throw an error, generally our program is to capture exception, do not catch this anomaly, this anomaly will continue to propagate upward.

What better way to print the exception stack and throw the error, my advice is to throw the error:

    • This can happen because of problems with the JVM, and perhaps other features, which should stop restarting and fix the problem immediately.
    • If the stack information is printed, then the next call will be an error, rather than simply throwing the error print stack information
4.2 Exceptions to assumptions that should not occur

We will take the above string, byte array example to illustrate, we have upgraded it, below is the incomplete code:

 Public Static String Bytetostr (byte[] bytes, string charsetname) {  returnnew  string ( Bytes, charsetname);}

What should I do, throw an exception? Catch exception print log? Neither of these approaches is good:

    • If you throw an exception: then the person who uses your tool class is still very headache, he must be in every call to your method of processing, either throw or catch, and he is thinking I passed a UTF-8, I must throw an exception, hard to die.
    • If the print log is captured: This is even more undesirable, if the user loses the wrong encoding type, then you will not be able to give any information to the caller (the print log can only be found after the error), the user believes that the write is correct and you also give the return value, which will also lead to a series of errors produced.

What to do in this case, the more recommended way is to package the runtime exception thrown:

 Public Static String Bytetostr (byte[] bytes, String charsetname) {  try  {    return  New  String (bytes, charsetname);   Catch (unsupportedencodingexception e) {    thrownew  runtimeexception (e);  }}

This solves two of the above problems.

4.3 The case that the hypothesis must be abnormal

Your code will definitely be out of the ordinary, then you should take it back to rewrite it. Unless you do not want others to call your method, such as an immutable container, the action class method throws an exception.

V. Some special cases of Exception 5.1 prevent abnormal loss

Exceptions are not lost when you are not actively annexing exceptions, but there is a special case to note that there is a return in finally (the code refers to the Java programming idea):

 Public Static void Exceptionsilencer () {  try  {    thrownew  runtimeexception () ;   finally {    return;  }}

In this case, the exception is lost and completely gone, so avoid using it and avoid using return in the finally.

5.2 Threaddeath Exception in thread

This exception is attributed to the error level, which is also described in the Java API:

Try Catch

That is, Threaddeath itself is an ordinary exception, this anomaly should cause the thread to die, but do not ascribe it to exception because the JDK developers also expect Java programmers most like the try catch exception and then swallow it, This will cause the thread that should die to continue to run, which should not be the case.

If your thread is often inexplicably disappearing, you can try to catch the exception, but remember to print out the relevant log and throw it back.

Six, the Java programming thought in the summary explanation

The following excerpt from the Java programming idea of the exception use guide, especially good, must be in-depth understanding:

    1. Deal with the problem at the right level. (Catch an exception if you know what to do with it.) )
    2. Resolve the problem and recall the method that generated the exception.
    3. Do a little patching, and then go around where the exception occurred.
    4. Calculate with other data in place of the value expected to be returned by the method.
    5. Try to finish what you can do in the current operating environment, and then toss the same exception to the higher level.
    6. Try to finish what you can do in the current operating environment and throw the different exceptions to the higher level.
    7. Terminating programs
    8. Simplification (if your anomaly mode complicates the problem, it can be very painful to use).
    9. Make class libraries and programs more secure.

Here's my idea in turn.

    • 1th: The above section has been introduced, here no longer explain
    • 2nd: The above is also introduced, is caused by external conditions, can be repeated to execute the code may be normal
    • 3rd: This kind of situation is actually annexation anomaly, for example, Network Crawler, when encounter dead link, throw connection exception, this time regardless of it can, don't it
    • 4th: Some programmers will design, when the user output error data caused by the exception, the use of a default value to replace, I do not like to do so, I will throw the exception to let users change, if you have to do so must print the relevant log
    • 5th: This situation depends on demand, if the requirements are either all successful, or do not do, then it is not suitable for this situation
    • 6th: ditto, but I don't quite understand this.
    • 7th: This is not the bar, there is an abnormal program hanging, it is too brittle, but when the program in normal startup process, if the exception is directly hanging out or reasonable, so that users modify the external conditions to ensure that the startup no problem, such as the user specified profile does not exist (perhaps he wrote the wrong path), Then do not use the default configuration, the program can be directly hung off, otherwise it will give the user a successful start in accordance with his configuration illusion.
    • 8th: This and the above mentioned use a runtime exception to ensure that the catch exception is a property.
    • 9th: This is the ultimate goal, considering all the circumstances, to eliminate the abnormal in the bud, too ideal.

Above is my understanding of the anomaly, hope can help people who need, if you can read carefully I believe you will have harvest, if the error please point out, prohibit reprint.

A brief analysis of Java anomaly System

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.