Preface
Try...catch...finally we often use it in our code, and have always felt that this thing is not very useful. Because in development, we always believe that our code is not error-prone. In this way, the problem comes, once our system has gone wrong, without them, the system will crash, reflected to the user, the user will not use the system.
One, Java exceptions
Exceptions refer to a variety of conditions, such as: File not found, network connection failure, null pointer, class not found, illegal parameters and so on. An exception is an event that occurs during an abnormal run, interfering with the normal instruction flow. Java describes various kinds of exceptions through the many subclasses of the Throwable class in the API. Therefore, Java exceptions are also exceptions, which are instances of Throwbale subclasses.
Java Exception class hierarchy diagram
As we can see, throwable as a class, there are two important subclasses:
Error: The program cannot be processed, and once encountered, the system crashes and cannot continue running, indicating a more serious problem in running the application.
Exception (Exception): An exception that the program itself can handle. Can generally be divided into two types: IO outflow and run exception.
second, handling abnormal mechanism
In Java applications, exception handling mechanisms: Throw exceptions, catch exceptions.
Throw exception: When a method error throws Yichang, the method creates the exception object and delivers the runtime system, which contains exception information such as the exception type and the state of the program when the exception occurred. Usually we throw an exception to the method that calls it with throw.
Catch exception: After the method throws a field, the runtime system will look for the appropriate exception handler. After the method throws an exception, the runtime system will look for the appropriate exception handler (exception handler). A potential exception handler is a collection of methods that persist in the call stack, in turn, when an exception occurs. An appropriate exception handler is the exception type that can be handled by the exceptions handler when it matches the type of exception thrown by the method. The runtime system starts with the method in which the exception occurred and then turns back to the method in the call stack until it finds the method that contains the appropriate exception handler and executes it. The runtime system terminates when the runtime system traverses the call stack without finding an appropriate exception handler. At the same time, it means the termination of the Java program.
Java technology requires different exception handling for run-time exceptions, errors, or exceptions that can be checked.
Because of the non-availability of runtime exceptions, in order to make the application more reasonable and easier to implement, Java rules that runtime exceptions are automatically thrown by the Java runtime system, allowing applications to ignore runtime exceptions.
Java allows the method to not make any throw declarations when the run method does not want to catch the error that may occur in the method's run. Because most error exceptions belong to a condition that can never be allowed to occur, it is also a reasonable exception that the application should not catch.
For all the exceptions that can be checked, the Java rule is that a method must catch, or declare the throw method. That is, when a method chooses not to catch an exception, it must declare that it will throw an exception.
The exception that a method can catch must be the exception that the Java code throws at some point. Simply put, the exception is always first thrown and then captured.
Any exception thrown in a method must use the throws sentence.
1. Catching Exceptions
Typically implemented using Try-catch or try-catch-finally statements.
(1), Try-catch
Instance:
public class TestException {public static void Main (string[] args) { int[] Intarray = new Int[3]; try {for (int i = 0; I <= intarray.length; i++) { intarray[i] = i; System.out.println ("intarray[" + i + "] =" + intarray[i]); System.out.println ("intarray[" + i + "] modulo" + (i-2) + "value: " + intarray[i]% (i-2));} } catch (ArrayIndexOutOfBoundsException e) { System.out.println ("Intarray array subscript out of bounds exception. "); } catch (ArithmeticException e) { System.out.println ("divisor is 0 exception. "); } SYSTEM.OUT.PRINTLN ("The program ends normally. "); } }
The above code captures two errors: divisor is 0 and array subscript out of bounds exception. Operation Result:
Intarray[0] = 0
Intarray[0] Modulo-2 value: 0
INTARRAY[1] = 1
INTARRAY[1] Modulo-1 value: 0
INTARRAY[2] = 2
Divisor is 0 exception.
The program ends normally.
We run to find that when the first error is caught, the system will no longer execute the code after the try, and the run first catches the error with a divisor of 0, so the end of the processing ends with the entire Try-catch statement.
Java describes the exception type through the exception class, which is shown in hierarchy 1 of the exception class. For an exception program with multiple catch clauses, you should try to put the catch clause that captures the underlying exception class in front of you as much as possible, and keep the catch clause of the exception class that captures the relative high level. Otherwise, the catch clause that captures the underlying exception class may be masked.
(2), try-catch-finally
Finally, no matter whether the catch is caught or not, it will run.
Illustration of the execution of the try-catch-finally statement:
2. Throw an exception
(1), throws throw exception
If an exception is possible for a method, but is not capable of handling the exception, you can declare the throw exception by using the throws clause at the method declaration. For example, a car may fail when it is running, and the car itself cannot handle the failure, so let the driver handle it.
The throws statement declares the type of exception to be thrown by the method when the method is defined, and if it throws a exception exception type, the method is declared to throw all exceptions. Multiple exceptions can be separated using commas. The syntax format for the throws statement is:
MethodName throws Exception1,exception2,.., exceptionn {
after throwing an exception to the caller using the throws keyword, if the caller does not want to handle the exception, it can continue to throw up, but eventually there is a caller who can handle the exception.
In general, we use exceptions, throw exceptions to the UI, and process them through the error page, which gives the user a better experience.
(2), throw throw exception
The throw usually appears in the function body to throw an exception of type Throwable. The program terminates immediately after the throw statement, and the code after it is not executed.
<span style= "FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;" >package Test; Import java.lang.Exception; public class TestException {static int quotient (int x, int y) throws myexception {//Definition method throws exception if (Y < 0 {//To determine if the parameter is less than 0 throw new myexception ("divisor cannot be negative");//exception information} return x/y; return value} public static void Main (String args[]) {//Main method int a = 3; int b = 0; The try {//Try statement contains a statement that could occur with an exception int result = Quotient (a, B);//Call Method quotient ()} catch (MyException e) {/ /Handle Custom Exception System.out.println (E.getmessage ()); Output exception information} catch (ArithmeticException e) {//Handle ArithmeticException exception System.out.println ("Divisor cannot be 0"); Output hint message} catch (Exception e) {//Handle other exception System.out.println ("Other exception occurred by program");//output hint message} }} class MyException extends Exception {//Create custom exception class string message;//define String type variable public myexceptio N (String errormessagr) {//parent class method message = ERRORMESSAGR; } public String GetMessage () {//overwrite GetMessage () method return message; }} </span>
It is important to note that throw throws only an instance object that can throw a class throwable or its subclasses.
If you throw a check exception, you should also declare the type of exception that the method might throw on the method header. The caller of the method must also check the exception that is thrown by the handle.
Summary:
Exceptions in the program can not be replaced, not to write, this is a very dangerous thing, the exception reflects the professionalism of a programmer, more can reflect a programmer's overall view.
Reference: http://blog.csdn.net/hguisu/article/details/6155636
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Java Exception Handling