Java basics-difference between exceptions and errors: Error and exception

Source: Internet
Author: User
Tags xsl
Error and exception


Understand the differences between exceptions and errors, and know what to do when you intercept an exception.
By josh Street

Many programmers do not realize that an error is different from an exception. When a problem occurs, this difference has important meaning for how to operate your code (see the tool bar, "Introduction error and exception "). As Mary Campione wrote in the Java tutorial (Java Guide), "an exception is an event that occurs during the execution of a program and interrupts normal command execution ." According to the explanation of the American Heritage Dictionary, an error is an action or instance that "deviates from an acceptable code behavior ."

So what is the difference between deviation and disruption? We can explain this as follows: If you are driving on a road and someone stops you, this is the interruption. If the car cannot be started, it is a deviation (unless it is my car, we think this situation isNormal).

What does this have to do with Java? There is a lot of relationship. Java has an interesting hierarchy of errors and exceptions (see figure 1 ).

Indeed, all the code using try {} catch (exception e) {} can only find half of your error. But whether or not you should intercept throwable depends on how you plan to handle it once you intercept it. A quick understanding of the subset of errors allows you to know the names of many classes, such as virtualmachineerror, threaddeath, and linkageerror. When you plan to intercept these errors, be sure you want to handle them because they are a serious problem and therefore an error.

Figure 1. "src =" http://www.fawcette.com/china/Java/2002_09/JavaException/Image/fig1sm.gif "align =" right ">
Figure 1.

But isn't classcastexception an error? No. A classcastexception-or an exception-is only one way that VM (Virtual Machine) notifies you. In this way, Vm lets you know that You (developer) have made an error, now you have a chance to modify it.

On the other hand, an error is a fault of the VM (although it can be a service of any system level ). Let's reference javadoc's definition of error: "error is a subset of throwable. It refers to a serious problem that a reasonable application cannot intercept. Most of them are abnormal ."

Therefore, errors are difficult to handle. Generally, developers (not you) cannot understand the nuances of handling these errors. In your work, what should you do when you think that an event is sufficient to be called a mistake?

First, remember that errors are thrown like exceptions, but they are only a little different. The method that throws an error does not need to declare what it is doing (in other words, the exception is unchecked ):

public void myFirstMethod() throws Exception    //Since it's an exception, I have to declare     //it in the throws clause {    throw new Exception();}public void mySecondMethod()    //Because errors aren't supposed to occur, you     //don't have to declare them. {    throw new Error();}

Note that several exceptions are unchecked. Therefore, the behavior is the same as the error: nullpointerexception, classcastexception, and indexoutofboundsexception are subclasses of runtimeexception, and runtimeexception and all its subsets are usually unchecked.

So how should you handle these annoying unchecked exceptions? You can intercept exceptions in the methods they may appear, but this method has a great deal of chance. This can solve a problem, but it will cause other unchecked exceptions to interrupt other parts of the Code. We should thank the threadgroup class for providing a good solution:

public class ApplicationLoader extends ThreadGroup{     private ApplicationLoader()     {          super("ApplicationLoader");     }     public static void main(String[] args)     {          Runnable appStarter = new Runnable()          {               public void run()               {                    //invoke your application                    (i.e. MySystem.main(args)}          }          new Thread(new ApplicationLoader(), appStarter).start();     }     //We overload this method from our parent     //ThreadGroup , which will make sure that it     //gets called when it needs to be.  This is      //where the magic occurs.public void uncaughtException(Thread thread, Throwable exception)     {          //Handle the error/exception.          //Typical operations might be displaying a          //useful dialog, writing to an event log, etc.     }

This method has greatly changed our programming. Think about it. In the past, when you executed an operation in your GUI, if an unchecked exception occurs, your GUI is usually in an abnormal state (the dialog box is still open, the button cannot be activated, and the pointer is in an error state), but this method is used, you can make the GUI return to its normal state and notify users of errors. You will feel good about this because you have compiled a high-quality application.

But this technique is not just for GUI. Server applications that use too many resources can use this method to release resources globally, which usually prevents the VM from entering an unstable state. As early as possible and as much as possible to intercept errors and handle them in a wise way, this is a difference between a great programmer and an ordinary programmer. Since you have read this article, it is obvious which programmer you want to become.


About Author:
Josh street is an architect of Bank of America who is mainly responsible for developing e-commerce solutions. His contact information is rjstreet@computer.org.

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.