Detailed exception (Exception) II

Source: Internet
Author: User
Tags finally block readfile stack trace throwable try catch
The abnormally large classification is divided into detection anomaly (checked exception) and non-detectable anomaly (unchecked exception). The detection exception is the exception that can be found in the compiler.
Non-detectable anomaly also includes error and Exception the error represents an exception that is not within the program, that is, from external exceptions: such as: Hard disk damage, system failure, etc. Exception refers to the internal exception of the program: generally refers to the program is the logic of the problem, or incorrect use of the API caused by the exception.
Both the instrumented exception and the non detectable exception are inherited from the Throwable class.
One: Method throws an exceptionThe Writelist method write exception handler in the Listofnumbers class is learned in the previous section. Sometimes it is appropriate to capture within the method. In other cases, however, it is more reasonable to have a method for further call stacks to handle this exception (it's better to let a methods further up the called stack Handle the exception), that is, not handled in this method Exception, but rather throws it to the method that calls the method to handle it. For example, if you provide a Listofnumbers class as part of a package class, you may not be aware of all users who use the package, that is, you do not know which other users will use this class, it is possible that classes under other packages will use this class, even if the case with this class is uncertain, in this case,    It might be a better way not to catch an exception, but rather let the call stack of this method be called further to handle it. If the Writelist () method does not capture a instrumented exception that appears inside it, the Writelist method must specify that it can throw these exceptions, and the following modifies the Writelist method to throw an exception instead of catching the exception, the following is the Writelist method cannot pass the original version of the compilation.
public void Writelist () {
	    printwriter out = new PrintWriter (New FileWriter ("OutFile.txt"));
	    for (int i = 0; i < SIZE; i++) {
	        out.println (' Value at: + i + = ' + list.get (i));
	    }
	    Out.close ();
	}

To define the Writelist method to throw two exceptions, add the throws statement in the Writelist method declaration, as follows:
	
	public void Writelist () throws IOException, arrayindexoutofboundsexception {
	    printwriter out = new PrintWriter (New Fi Lewriter ("OutFile.txt"));
	    for (int i = 0; i < SIZE; i++) {
	        out.println (' Value at: + i + = ' + list.get (i));
	    }
	    Out.close ();
	}

Note: ArrayIndexOutOfBoundsException is a non-instrumented exception and does not force this exception to be thrown, as is the case with the following.
public void Writelist () throws IOException {
	    PrintWriter out = new PrintWriter (New FileWriter ("OutFile.txt"));
	    for (int i = 0; i < SIZE; i++) {
	        out.println (' Value at: + i + = ' + list.get (i));
	    }
	    Out.close ();
	}
two: How to throw an exceptionBefore you catch an exception, there must be some code that throws out some exceptions, and the code that throws the exception includes: Your own code, code written by others in the Java platform's package, or the Java Runtime Environment, which is always decorated with throw statements, regardless of who throws an exception.
You may have noticed that the Java platform provides a wide variety of exception classes, all of which are subclasses of the Throwable class, where exception classes appear as a way of distinguishing between various exception classes during program execution.
You can create your own exception class declaration that appears in the class you are writing, and if you develop a package, you may have to create your own exception class that allows users to differentiate between your errors and the other packages under the Java platform, and you can create an exception chain.
1: Throwing statementsAll methods use the throw statement to throw an exception, the throw statement requires a separate argument, a Throwable object, the Throwable object is a subclass of the Throwable class, and the following is an example of a throw statement.
Throw somethrowableobject;
To take a look at the usage of the throw statement, the Pop method is a method in a class that implements a common stack object, which removes an object from the top of the stack and returns the object as follows:
Public Object pop () {
	    object obj;

	    if (size = = 0) {
	        throw new emptystackexception ();
	    }

	    obj = Objectat (size-1);
	    Setobjectat (size-1, null);
	    size--;
	    return obj;
	}
Pop methods Check if there are still some elements in the stack, if the stack is empty, the pop method instantiates a new Emptystackexception object (the member class under Java.util), and throws it, Note that you can only throw objects that inherit from the Throwable class.
Note: The declaration of a method does not contain a throws statement, and the emptystackexception exception is not a instrumented exception, so the pop method does not necessarily declare its appearance.
2:throwable class and its subclassesClasses that inherit from the Throwable class include inheriting directly from the Throwable class and indirectly inheriting from the Throwable class, as shown in the following illustration: The Throwable class has two direct subclasses: Error and Exception
Throwable class and its child class structure diagram 3:error classWhen the JVM has a dynamic link failure or other difficult failure, the JVM throws an error, and a simple program is usually not able to capture or throw Errors.
4:exception classMost programs throw or capture objects originating from the exception class, and a exception class illustrates the emergence of a problem, but it is not a serious system-level problem, most of which are written in the same way as errors, throwing or capturing such exceptions.
The Java platform defines a number of exception subclasses that show a variety of possible exceptions, such as a illegalaccessexception description that does not find a specific method. Negativearraysizeexception describes an array of program views that create a negative size.
A subclass of Exception runtimeexception is a description of the improper use of the API, usually in the process of using logic problems, such as NullPointerException is a run-time exception, This exception occurs when a method tries to access a null reference. Two: Abnormal chain (Chained exceptions)In a program, you often respond to an exception by throwing a method of an exception. In fact, the first exception causes the second exception, and it's important to know when an exception causes another exception. The anomaly chain (Chained exceptions) will help us to do this thing.
Here are some methods and constructs for supporting chained exceptions in the Throwable class
Throwable getcause ()
throwable initcause (throwable)
throwable (String, Throwable)
throwable (Throwable)

The parameters of the Throwable type in the Initcause method and the Throwable constructor represent the current current exception. The current exception caused by the Getcause method return. The following code shows how to use the exception chain:
try {

} catch (IOException e) {
    throw new Sampleexception ("Other IOException", e);
}

In this example, when the IOException exception is caused, the new Sampleexception exception object with the original driver is created, added to the back of the exception chain, and thrown to a more advanced exception to handle. 1: Access stack trace information (stack trace information)Now assume that higher-level exceptions want to print stack trace information in their own format. Definition: Stack traces (stack trace) provide information about the current thread execution history, list the class names and method names that are invoked when an exception occurs, and stack trace is a useful debugging tool, and you will see the benefits when an exception is thrown.
The following code demonstrates how to invoke the Getstacktrace method of an exception object:
Package test.exception;

public class Divisionzero {public
	static void Main (string[] args) {
		try{
			System.out.println (5/0);
		} catch (Exception cause) {
		    stacktraceelement elements[] = Cause.getstacktrace ();
		    for (int i = 0, n = elements.length i < n; i++) {       
		        System.err.println (elements[i].getfilename ()
		            + ":" + Element S[i].getlinenumber () 
		            + ">>"
		            + elements[i].getmethodname () + "()");
		    }
	}}


The above program can print out the corresponding information.
2:logging APIThe following example prints the exception information to the OutFile.log file:
Package test.exception;

Import java.io.IOException;
Import Java.util.logging.FileHandler;
Import Java.util.logging.Handler;
Import Java.util.logging.Level;
Import Java.util.logging.Logger;

public class Divisionzero {public
	static void Main (string[] args) {
		
		try {
			System.out.println (5/0);
		    Handler Handler = new Filehandler ("Src/resource/outfile.log");
		    Logger.getlogger (""). AddHandler (handler);
		    
		} catch (IOException e) {
		    Logger Logger = Logger.getlogger ("Package.name"); 
		    Stacktraceelement elements[] = E.getstacktrace ();
		    for (int i = 0, n = elements.length i < n; i++) {
		        logger.log (level.warning, Elements[i].getmethodname ());
		    }
		}
	}
}
Three: Create an exception classWhen faced with an exception class that is thrown, you can use some other people's written classes---Java platform to provide a lot of exceptions you can use, or you can write an exception class of your own, if the answer to the following questions is ' yes ' you can create your own exception class. Otherwise, you can use other people's exception classes. 1: The exception type you need does not have a description in the Java platform:. 2: Other suppliers or callers can distinguish your exception from the exception being thrown. 3: More than one associated exception is thrown in the code. 4: If you use some other exception, the user will access these exceptions. A similar question, your bag is independent.
1: An example
Suppose you write a class of linked list that supports the following methods: Objectat (int n)-Returns an object at nth position, if this argument is less than 0 or greater than the total number of objects in the list throws an exception. Firstobject ()-Returns the first object that throws an exception when there is no object in the list container. indexOf (Object o)-Finds the index of a particular object, returns the position of the object in the list, and throws an exception if the object does not exist in the list. The lined list class can throw a lot of exceptions, and it's easy to catch all the thrown exceptions through an exception handler in the linked list. If you plan to describe the linked list in a package, all the relevant code should be in the package, so the linked list should provide its series of exception classes. The following figure is a description of the structure of the linked list exception class and its subclasses.
Examples of exception class inheritance 2: Select a subclassSome other subclasses can also be used where linkedlistexception can be used, and when these subclasses are familiar, many situations use the exception and the Linkedlistexception parent class completely irrelevant. So the linkedlistexception parent class is an exception, generally not. The type of exception object thrown in most written programs is exceptions,errors is usually a more serious case, which will prevent the JVM from running if the system hardware is compromised, the system fails, and so on.
Note: For the readability of your code, it is a good programming practice to append exception string names to all of the subclasses that indirectly or directly inherit from the exception class. four: Controversy over the non-detectable anomaly (Unchecked exceptions-the controversy)
Because the Java language does not require method captures or specifies specific non detectable exceptions (Runtimeexception,error, and their subclasses), programmers may be interested in simply throwing a non-detectable exception in the code, or let all of their exception subclasses inherit from RuntimeException, both of which make the programmer not compile errors and not catch the specified exception interference, although this seems to be convenient for programmers, but when others use the class you write may cause some problems. Therefore, this operation is not recommended.
Why does the designer force to specify all the detected exceptions thrown in one method? Throws an exception on a method as part of the common programming interface for this method. The caller of the method must know what exception the method throws, in order for the caller to decide what to do with this method, in the programmatic interface of the method, the exception is part of the method's argument and return value.
The following question is: If a method API document is well written, including the exception it throws, why not specify a Run-time exception in this method? Runtime exceptions explain the problems that occur when the program is running, and the client code for these exceptions is not reasonably recoverable from these exception problems, or it cannot be handled in some other way. These exception problems include arithmetic operations exceptions (for example, 0); point to (Reference) an exception (for example, an attempt to access a reference to a null object); An index exception (for example, an attempt to access an index of an array that is too large or too small).
Runtime exceptions can appear in many parts of the program, in other words, there are a lot of different run-time exceptions, adding run-time exceptions to each method declaration reduces the transparency of the program (making the program not very clear), and in order to make the program clearer and more explicit, So the compiler does not have to have the programmer capture or specify a particular exception (even if you can capture or specify).
A common example of throwing run-time exceptions is when a user makes a bad call to a method, for example: If a parameter is incorrect to NULL, the method can check that if a parameter is null, the method may throw a nullpointerexception, The exception is a non-detectable exception (unchecked exception).

In general, you don't throw run-time exceptions or simply create a runtimeexception subclass, because you don't want to be bothered by specifying in the method that you want to throw an exception.
The following is an important rule: If the client code can reasonably recover from an exception, the exception is a detectable exception (checked exception), which is a non-detectable exception (unchecked exception) if it is not reasonably recoverable from the exception.
Five: The advantages of using exceptionsNow that you know the exceptions and how to use them, let's take a look at the benefits of using exceptions in your programs.
1: Isolate the error handling code from the business rule codeWhen an unconventional event occurs in a major logical code, the exception is separated from the code to provide meaningful information.
In traditional programming, error detection, reporting, and processing often make code feel confusing, for example: The following is a pseudo code method that reads files into memory.
ReadFile {
    Open the file;
    determine its size;
    Allocate that much memory;
    Read the file into memory;
    Close the file;
}

At first glance: This function is simple, but it ignores all of the following possible errors: If the file cannot be opened, what will happen. What happens if you can't determine the length of the file. What to do if there is not enough memory to allocate. What to do if you fail to read this file. What if the file cannot be closed.
To handle the above problem, the ReadFile function must have more code to do error detection, reporting, and handling errors, and here is an example of a possible function.
Errorcodetype ReadFile {
    Initialize errorcode = 0;
    
    Open the file;
    if (Thefileisopen) {
        Determine the length of the file;
        if (gotthefilelength) {
            allocate so much memory;
            if (gotenoughmemory) {
                read the file into memory;
                if (readfailed) {
                    errorcode =-1;
                }}
            else {
                errorcode =-2;
            }}
        else {
            errorcode = -3;< c16/>} close the
        file;
        if (thefiledidntclose && errorcode = = 0) {
            errorcode =-4;
        } else {
            errorcode = errorcode and-4;
  }
    } else {
        errorcode =-5;
    }
    return errorcode;
}

There are a lot of places that need error detection, reporting, and processing to make the code look messy, and, worse, the logic of the code is blurred, so it's not good to understand what the above code is doing. Many programmers choose to ignore the above problems, but it is not advisable.
Exceptions allow you to write down the main processes and to handle them uniformly in other places, if the above examples are handled in an unusual way, as follows:
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
    }
}

Note: Exceptions do not disperse the effort to solve the main logic, but they can help you organize your code more efficiently.
2: Propagate errors (Error) to call stackThe ability to propagate errors until the call stack of the method, assuming that the ReadFile method is the fourth method in a nested invocation of the method of some column main program, METHOD1 calls METHOD2,METHOD2 call Method3,method3 call ReadFile, as follows:
method1 {call
    method2;
}

METHOD2 {call
    method3;
}

method3 {call
    readFile;
}

Assuming that only method1 cares about the exceptions that occur in the ReadFile method, common error notification techniques Force METHOD2 and METHOD3 to propagate the error code returned by the ReadFile method to the top of the call stack until it finally arrives at Method1. Because only method1 care about the ReadFile method's exception. The calling mode is as follows:
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;
}

When invoked, the JVM searches the call stack backwards to find some way to care about handling a particular exception (METHOD1), and some other method can continue to press the exception within its method, allowing the method to be further captured in the call stack, so only this method that needs to be detected cares about the call.
method1 {
    try {call
        method2;
    } catch (Exception e) {
        doerrorprocessing;
    }
}

Method2 throws Exception {call
    method3;
}

Method3 throws Exception {call
    readFile;
}

The above method shows that an exception can be thrown by specifying a specific throws statement in the declaration of a method.
3: Classification clear, distinguish the error type
Because all exceptions thrown in the program are objects, and the classification of exceptions is naturally the result of class inheritance, examples of exception class classifications in the Java platform are in the Java.io package, IOException and its subclasses, when I/O is needed, IOException is a common statement, Its subclasses represent more specific errors, such as FileNotFoundException, which represents an error that does not find a file at a specific path in the hard disk.
catch (FileNotFoundException e) {
    ...
}

Some methods can capture common exceptions after categorization by specifying a superclass of a particular exception in a catch statement. For example, all I/O exceptions are caught, although there are many specific types, but the exception handler is able to catch all I/O exceptions only if you specify IOException. As follows:
catch (IOException e) {
    ...
}
The above processing will be able to capture all I/O exceptions, including filenotfoundexception,eofexception, and so on, to be able to view more detailed information in a catch statement block by printing this stack trace (stack trace).
catch (IOException e) {
    //Output goes to System.err.
    E.printstacktrace ();
    Send Trace to stdout.
    E.printstacktrace (System.out);
}

You can even handle exceptions as follows:
A (too) general exception handler
catch (Exception e) {
    ...
}
Exception is a direct subclass of the Throwable class, so the exception program will catch all exceptions, as long as the exception handler wants to capture, and if you want your program to catch all the exceptions, you can do so in this way. Then print out the error message to exit.
In most cases, exception handlers should catch specific exceptions, and the best recovery strategy is achieved by performing a catch-specific exception. In fact, without capturing a particular exception, the exception handler must adapt to all possible exceptions, and the exception handler catches too much generalization that causes more errors, which is not what good code is expected to produce.
Note: You can use the large classification of exceptions to handle some exceptions. You can also specify specific exceptions to distinguish between other exceptions in the program, and to make the type of the exception more granular.
Summary: Using exceptions in your program indicates that an error may occur. In order to throw an exception, you can use the throw statement and then follow an exception object (a subclass of Throwable to provide specific information that throws an exception), and a non-instrumented exception that is not captured inside the method must add the throws statement to the declaration of the method.
The program can catch exceptions using a try Catch finally block. A try block contains code block catch blocks that may have an exception that is called an exception handler that handles a particular exception. Finally blocks are blocks of code that are guaranteed to execute (provided the JVM has no other exception exits), and finally blocks are closing files, restoring resources, and cleaning up other resources. A try statement block can append at least one catch block or a finally block and multiple catch blocks. The Exception class object shows the type that throws the exception, and the exception object can contain more exception information, in which an exception can point to the exception that caused it ...
The abnormally large classification is divided into detection anomaly (checked exception) and non-detectable anomaly (unchecked exception). The detection exception is the exception that can be found in the compiler.
Non-detectable anomaly also includes error and Exception the error represents an exception that is not within the program, that is, from external exceptions: such as: Hard disk damage, system failure, etc. Exception refers to the internal exception of the program: generally refers to the program is the logic of the problem, or incorrect use of the API caused by the exception.
Both the instrumented exception and the non detectable exception are inherited from the Throwable class.

Practice:
try {
    
} finally {
   
}
The above code is legal.
try {

} catch (Exception e) {
   
} catch (ArithmeticException a) {
    
}
The above code error, the first catch exception has caught all the exceptions, the second is redundant, the order reversed is OK.
A:int[] A;  a[0]=0; --compilation error, the array is not initialized and cannot be compiled. B:JVM started running your program, but the JVM could not find the Java platform class---error C: program read stream, reached the end of the stream,-------no exception D: After reaching the end of the stream and before closing the stream, the program tries to read the information again in the stream, checked Exception (detection of abnormal)









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.