"Getting Started with Java" DAY16 Java exception handling (bottom)

Source: Internet
Author: User
Tags throw exception throwable

Today, we continue to explain the exception handling mechanism in Java, which mainly introduces the main members of the exception family, custom exceptions, and the correct posture of exception handling.

Exception family

A picture wins thousands of words, first look at a picture.

Exception this is a parent class, it has two sons, IOException and RuntimeException, each son is very able to live, so it has a bunch of grandchildren, but in fact, the exception family has a big thing, that is throwable, This is an interface, look at the name to know the meaning, is "can be thrown" well, it also has a half brother, that is the error, this guy is good, error class is generally referred to virtual machine-related problems, such as system crashes, virtual machine errors, insufficient memory space, method call stack overflow and so on. Catch statement, not only can catch live exception, can catch the error (what?) Are you really going to catch the Error?? Cheng classmate, you sit down first. In general, the error is not captured, and for such errors the Java compiler does not check them. For this kind of error caused by the application interruption, only by the program itself cannot be recovered and prevented, encountered such errors, it is recommended to let the program terminate. Unless you are sure that you can handle it correctly, Cheng students should sit down (funny).

Unchecked Exception and checked Exception

You may have a face to the head,??? , what is this? The exception is also divided into factions, unchecked exception means "Unchecked exception", Checked exception nature is "checked exception", derived from error or RuntimeException exception is called unchecked exception, All other exceptions become checked exceptions. The question comes, why should we distinguish between these two anomalies?

We can look at the diagram above, and we can see that both the RuntimeException and the error are caused by errors within the program, such as null pointers and arithmetic exceptions in the previous article. And checked exception is mostly caused by external factors, such as the file can not find the exception, which is the virtual machine can not control the situation, when the exception, the virtual machine can only a face, do not know how to be good, so when it can happen, you must use try. Catch to capture it, and for unchecked Exception, most of it is caused by code, so as long as the code is well-written enough, it will not throw such an exception, so it does not force the requirement to capture.

So the reason is actually very simple, the compiler will check whether you provide an exception handling mechanism for all checked exceptions, such as when we use Class.forName () to find the class object of a given string, if we do not provide exception handling for this method, compile cannot pass. The meaning of the checked exception is to let you know that this place is possible to throw an exception, you have to pay attention to, quickly caught.

Custom exceptions

So how do you customize an exception? In fact, it is very simple, just inherit the exception class just fine. Look at the chestnuts below:

 Public classMyExceptionextendsException { Publicmyexception () {Super(); }     Publicmyexception (String message) {Super(message); }     Publicmyexception (String message, throwable cause) {Super(message, cause); }     Publicmyexception (Throwable cause) {Super(cause); }    protectedMyException (String message, throwable cause,BooleanEnablesuppression,Booleanwritablestacktrace) {        Super(message, cause, enablesuppression, writablestacktrace); }}

MyException inherits the exception class, overrides the constructor, and does not add its own logic, but invokes the method of the parent class. You see, customizing an exception is really simple. See this you may be puzzled again, this Nima seems to give exception changed a name, what use???

Don't worry, don't worry, you forget, exception is not only can be captured, or can be actively thrown, so when encountering certain circumstances, we can actively throw an exception, and then in the call to catch it, get exception information, if directly with exception, then capture, Will catch all the anomalies, the catch should not be captured, then we can not distinguish which are the exceptions that we have thrown out, so that the exception can not be special processing.

Correct posture for exception handling

Next, we will briefly introduce an exception-handling method, which is commonly used in practical use.

In some large, modular software development, once an anomaly occurs in one place, like the domino effect, a series of anomalies will occur. Assuming that the B module needs to call the method of the A module, if an exception occurs in the A module, then B will not be able to complete the exception, but B when throwing an exception, the exception information of a will be masked out, which will make the source information of the exception is lost. Using the chain of exceptions, you can concatenate the exceptions of multiple modules so that the exception information is not lost.

An exception chaining is the construction of a new exception object for a parameter with an exception object. The new heterogeneous object will contain information about the previous exception. This technique is mainly implemented by a function with Throwable parameters for the exception class. As an exception to this argument, we call him the root cause anomaly (cause). If you are careful, you will find that the above Li Zili also has a thing called cause, yes, that is it, in the new exception, the previous exception information passed to the constructor. The following is a simple chestnut to illustrate:

 Public classTest { Public Static voidMain (string[] args) {System.out.println ("Please enter 2 Addend"); intresult; Try{result=Add (); System.out.println ("Result:" +result); } Catch(Exception e) {e.printstacktrace (); }    }    /*** Perform addition calculations*/    Private Static intAdd ()throwsException {intresult; Try{List<Integer> nums =getinputnumbers (); Result= Nums.get (0) + nums.get (1); }Catch(inputmismatchexception immexp) {//chaining: Constructs a new exception object as a parameter to an exception object.             Throw NewException ("Calculation failed", Immexp); }        returnresult; }    /*** Gets the integer entered*/    Private StaticList<integer>getinputnumbers () {List<Integer> nums =NewArraylist<>(); Scanner Scan=NewScanner (system.in); Try {            intNUM1 =Scan.nextint (); intnum2 =Scan.nextint (); Nums.add (NewInteger (NUM1)); Nums.add (NewInteger (num2)); }Catch(inputmismatchexception immexp) {ThrowImmexp; }finally{scan.close (); }        returnNums; }}

The output is as follows:

  Please enter 2 addend d djava.lang.Exception: Calculation failed at Com.frank.chapter17.Test.add (test.java:
    35) at Com.frank.chapter17.Test.main (Test.java:  18) caused by:java.util.InputMismatchException at Java.util.Scanner.throwFor (Scanner.java:  864) at Java.util.Scanner.next (Scanner.java:  1485 2117 2076 47) at Com.frank.chapter17.Test.add (Test.java:  311 more 

It can be seen that when the input is not an integer, an exception occurred, in the Getinputnumbers method does not handle the exception, but will continue to throw it, after the exception is caught in the Add method, with the exception as the construction parameters, re-throw an exception, from the printout of the information can be seen, Not only the second throw exception information, the first output information mismatch exception details are also included in the inside, cohesion in caused by, forming an abnormal chain, so that we can quickly troubleshoot the problem.

At this point, the exception is explained, I hope to bring some inspiration and thinking, if you think it is OK, remember to move the small hand point recommendation, so that more people can see, also welcome attention to my blog, will continue to update. If there is anything bad about the place ... Emmmmmm, you come to beat me (flee)

"Getting Started with Java" DAY16 Java exception handling (bottom)

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.