Throw out countless exception, but what is exception? Unravel the mystery of exception ...

Source: Internet
Author: User

Java exceptions

What is an exception? Definition: When a program is running, there are instructions for the non-normal execution process, then an event object is generated, which is referred to as an exception (Exception) in Java.
An exception was an event, which occurs during the execution of a program, which disrupts the normal flow of the program ' s I Nstructions.


Exception handler: When an exception occurs, the JVM will look for a handler to handle the exception.
The following tree JVM calls the procedure and the handler call procedure, as you can see, the handler process is reversed.






Exception classification: Exceptions are divided into three main categories:
Error, which means that the exception is very deadly and does not need to be caught by an abnormal handler.
Checked Exception: The exception that is inspected is the exception that is expected by the user, usually the user takes the appropriate action to try to recover from the exception and needs to be caught by an exception handler.
Runtime Exception: A runtime exception, usually a bug, that is typically used to indicate that the exception is not expected by the user and does not need to be caught by an exception handler.



Syntax structure: TRY syntax structure:
try {
Code
}
Catch and finally blocks ...


CATCH syntax structure:
try {


} catch (Exceptiontype name) {


} catch (Exceptiontype name) {


}


Finally syntax structure:
try{


}catch (exceptiontype name) {


}finally {


}


The structure that throws and catches exceptions directly in the method:
public void Method1 () throws exceptiontype{


}


Throw an exception directly in the method
public void Method1 () {
if (Index < 0) {
throw new Emptystackexception ();
}
}

The role of the exception: First look at a method, using pseudo-code ...
ReadFile {    open the file; determine its size; Allocate that much memory; Read the file into memory; Close the file;}

In this method, we will perform the following steps 1 Open File 2 View file size 3 opening up memory space 4 read file contents into memory 5 close file
However, if this method appears the following problem 1 file cannot be opened 2 file size unpredictable 3 memory space is not enough 4 if the read file failed 5 close file failed
If exceptions are not available to handle these exceptions, what is the code like?
errorcodetype  readFile { Initialize errorCode = 0;      Open the file;          if ( thefileisopen ) {  determine the length of the file;              if ( gotthefilelength ) {  allocate that much memory;                  if ( gotenoughmemory ) {  read the file into memory;                  if ( readfailed ) {errorCode =-1;            }} else {errorCode =-2;        }} else {errorCode =-3;          close the file;          if ( thefiledidntclose  &&  errorCode  = = 0) {ErrorCode =-4;        } else {errorCode = ErrorCode and-4;    }} else {errorCode =-5; } return errorCode;} 
Each time the client calls this method, it is necessary to determine the status code returned, so as to decide what to do next ... Like what:
int status = ReadFile (); switch (status) {case-1: do something...case-2: Do someting ...}


This kind of code will drive you crazy, especially after a period of time, you come back to look at the code, you will find that the readability is particularly poor, if you add some new status code in ReadFile (), then the client's code needs to be changed together, which will cause the maintenance of destructive work, And it's easy to introduce new bugs.


Here's the code after using the exception:

ReadFile {    try {        open the file;        determine its size;        Allocate that much memory;        Read the file into memory;        Close the file;    } catch (fileopenfailed) {       dosomething;    } catch (sizedeterminationfailed) {        dosomething;    } catch ( memoryallocationfailed) {        dosomething;    } catch (readfailed) {        dosomething;    } catch ( fileclosefailed) {        dosomething;    }}

With exceptions, we can make the code more readable and not change the client's code if the new exception is added.


Let's take a look at another column.

method1 {call    method2;} METHOD2 {call    method3;} method3 {call    readFile;}
This is a method call stack, Method Method1 () called METHOD2 () calling method () 3 calls ReadFile ()

If the exception handling mechanism is not used, then each method will be forced to diagnose the error, which is quite troublesome, the following code:

method1 {    Errorcodetype error;    Error = Call method2;    if (error)        doerrorprocessing;    else        proceed;} Errorcodetype method2 {    errorcodetype error;    Error = Call method3;    if (Error)        return error;    else        proceed;} Errorcodetype method3 {    errorcodetype error;    Error = Call ReadFile;    if (Error)        return error;    else        proceed;}

Well, after reading, you'll be distracted by a lot of irrelevant code, all sorts of mess ...

Here we use exceptions to handle:

method1 {    try {call        method2;    } catch (Exception e) {        doerrorprocessing;    }} Method2 throws Exception {call    method3;} Method3 throws Exception {call    ReadFile;}

We only deal with exceptions in the only way we care ... The moment the world is beautiful.


In addition, exceptions can help us classify some of the errors. For example, in java.io, a variety of IO errors are required, such as open file failure, Access file failure, shutdown output stream failure, etc., we can boil these exceptions to IOException, from a higher level to look at the problem.


Custom exceptions: Typically, if you are developing a toolkit and an exception occurs, the user can customize the exception directly. The customization of the exception is very simple, and usually the class name represents the error category. such as: Illegalargumentexception,ioexception,negativeindexexception,filenotfoundexception, etc... One thing to note, however, is that it is important to choose an inherited exception class. If the error is unpredictable and belongs to a bug, you can inherit runtionexception or inherit exception.



Summary: Exceptions give the program a higher level of flexibility and make the code easier to understand. So it is very important to use the exception correctly. When catching an exception, it should be to do the specific type of exception, many people lazy, directly in each method throws Exception ... This can cause great difficulty in debugging bugs. For example, if the exception is thrown in a stack of 10 methods, then the exception chain is very large and it is difficult to locate the wrong location. Similarly, you cannot randomly catch exceptions or even throw them away, as in code Try{}catch (Exception) {ignore ...}. The program is clearly wrong, but the console has no output, which is definitely a big pit. So the catch exception is generally: can handle the exception, then you can catch the exception, if not, then throw an exception, throw to the caller to determine the handling of the exception.

Throw out countless exception, but what is exception? Unravel the mystery of exception ...

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.