First, what is abnormal?
There is an exception different from normal, and normal is not the same, there is an error to error. In java, the current method of preventing or scope normal operation, called exceptions.
Second, abnormal system
Java as the abnormal object to handle and define a base class for all exceptions as java.lang.Throwable superclass. Java API has been defined in a number of exception classes, these exception classes are divided into two categories, error and exception Error Exception.
Throwable divided into two different branches:
Error: It said they did not want to be captured or program is unable to handle the error. Error class and throw objects generated by the Java Virtual Machine, has nothing to do with the operation of most of the error code writers performed.
Exception: It represents the unusual circumstances of the user program may capture or abnormal program can handle. Exception and its subclasses, send run-time program on behalf of various non-event expectations. Can be used by Java exception handling mechanism is the core of exception handling.
The difference between Error and Exception: Error usually catastrophic fatal error, the program is beyond the control and treatment, when these exceptions occur, Java Virtual Machine (JVM) will generally choose to terminate the thread; Exception under normal circumstances can be programmed process, and to deal with these exceptions should be possible in the program.
The Javac exception handling requirements for the exception category is divided into two categories:
Non-abnormalities (unckecked Exception) : Error and RuntimeException, and their subclasses. javac at compile time, and are not prompted to find such anomalies are not required to handle these exceptions in the program, for these anomalies, we should amend the code, rather than by exception handler. Common RuntimeException:
ArrayIndexOutOfBoundsException (array subscript out of range)
A NullPointerException (null pointer exception)
ArithmeticException (arithmetic exception)
MissingResourceException (loss of resources)
ClassNotFoundException (class not found)
Abnormalities (the checked Exception) : In addition to other abnormalities of RuntimeException and Error. javac mandatory for such programmers to make preliminary abnormal processing (using try catch finally or throws). In either capture process with try-catch statement and deal with it, or throw it with a throws clause to declare, otherwise the compiler will not pass. This anomaly is normally provided by a program operating environment caused. Because the program can be run in a variety of unknown environments, programmers can not intervene and how users use the program prepared by him, so the programmer should be prepared for such an abnormal time. As SQLException, IOException, ClassNotFoundException etc.
If you only consider Exception, the non abnormalities (unckecked exception) is equivalent to RuntimeException, are equivalent to unsolvated abnormalities runtime exception.
Third, the exception handling
Exception handling mechanism and catch exceptions thrown into
Throws an exception: unable to obtain the necessary information in the current environment to solve the problem, you can do is jump from the current environment, and to submit questions to the upper-level environment, which is what happens when thrown an exception. After an exception is thrown, there will be a few things ensue. First of all, I like to create ordinary objects, like the use of java heap create a new exception object in; then, the current execution path (has been unable to go on) is terminated, and from the pop-up of exception object references in the current environment. In this case, exception handling mechanism to take over the program, and start looking for an appropriate place to continue executing the program, the right place is the exception handler or exception handler, its task is to recover from the error state program in order to make the program either change One way running, or continue running forever.
Catch exceptions: after method throws an exception, the runtime system will be converted to find suitable exception handler (exception handler). Potential exception handler is in turn retained collection method in the call stack when an exception occurs. When a match type of abnormality and method of abnormality type of exception thrown processor can handle, i.e. the appropriate exception handler. The system starts to run from the abnormal method, the method call stack in order to check back until the method containing the appropriate exception handler to find and execute. When operating the system walks the call stack without finding an appropriate exception handler, the runtime system is terminated. At the same time, the termination means that Java programs.
Java exception handling involves five keywords, namely: try, catch, finally, throw, throws:
try - for monitoring. The code will be monitored (may throw an exception code) placed inside the try block of statement, when an exception occurs within the try block, the exception will be thrown.
catch - used to capture the exception. catch used to capture an exception occurs in the try block.
finally - finally statement block will always be executed. It is mainly for the recovery of material resources opened in a try block (such as database connections, network connections and disk files). Only finally block, after the execution is complete, it will come back the try or catch block return or throw statement, if finally used in the statement termination method of return or throw, etc., then it will not jump back to perform, direct stop.
throw - for throwing an exception.
throws - used in the method signature, the method used to declare an exception might be thrown.
Catch exceptions: try catch / try catch finally
1, try-catch statement
try { // exception code area may be generated, but also a surveillance zone } the catch (ExceptionType1 E) { // catch and handle type ExceptionType1 try thrown exception } the catch (ExceptionType2 E) { // caught and handled try throw an exception of type ExceptionType2 exception }
2、try-catch-finally
try { // exception code area may be generated } the catch (ExceptionType1 E) { // catch and handle type ExceptionType1 try thrown exception } the catch (ExceptionType2 E) { // catch and handle type is thrown try ExceptionType2 exception } the finally { // whether it is abnormal, finally block code will be executed }
3, the order codes try-catch-finally blocks:
When A) try not to catch exceptions, the try block of statements to be executed sequentially, skipped catch. If there finally finally block is executed, otherwise subsequent code.
When B) try to capture the exception, if there is no matching catch clause, the JVM to the exception handling. If finally there is, the code of which is still to be executed, but the code after finally not be executed.
When C) try to capture the exception, if there is a matching catch, the catch block skip execution process. If there finally finally block is executed, execution of the finally finished after the subsequent code block; otherwise directly execute the subsequent code. Also note that the code after try block exception occurred is not performed.
important point:
1, try block and the catch block local variables local variables (including abnormal variable), and finally local variables can not be shared between them.
2, each processing block is used to catch an exception. Matching an exception catch block in the order from the top, look, only the first matching catch will be performed. Matching, not only operation an exact match, but also to support parent class matches, therefore, if there are a plurality of parent-child relationship exception type catch in the same try block, a subclass should be placed in front, on the back of the parent class exception, thus ensuring each catch block has the meaning of existence.
3, java, the task is to perform exception handling control flow transfer to the point where the exception can handle this anomaly places. In other words: When a function abnormalities occurred in a statement, this statement behind the statement will not be executed, it lost focus. Execution flow jumps to the exception handling catch block nearest match to perform, after the exception is handled, execution flow will be followed in the "process of this exception, the catch block" is followed by the implementation of
summary:
1, regardless of wood or abnormal try and catch the return values return, finally block of code will be executed;
2, finally is best not to include return, otherwise the program will exit early, will return to try to cover or catch the return value saved.
3. e.printStackTrace () may output abnormality information.
4. return value of -1 is written diet throwing an exception.
5. If the method of try, catch, finally no return statement, return the results of these three statements other than block is called.
6. finally performed before returning to the calling function after the try return.
Then look at two interesting code:
Code One:
public class TestFinally { public static void main(String[] args){ int[] a = test1(); System.out.println(a[0]); } public static int[] test1(){ int[] a = new int[10]; a[0]=1; try{ a[0]=2; return a; }catch(Exception e){ e.printStackTrace(); }finally{ A [ 0] =. 3 ; System.out.println ( "implementation of the finally" ); } return A; } }
Code II:
public class TestFinally { public static void main(String[] args){ System.out.println(test1()); } public static int test1(){ int i= 1; try{ i=2; return i; }catch(Exception e){ e.printStackTrace(); }finally{ i =3; System.out.println("执行了finally"); } return i; } }
Why the first piece of code in the try finally covering the return, and the second piece of code does not cover it?
In the process of debugging debug, try the return statement is executed twice, the first execution of a return statement in the try, not the real return, that is, but will return in the calculation expression, then save the results in a temporary stack, and then finally execute the statement, the final result will be temporarily removed from the stack before return. Therefore, in the first paragraph of the code, the address stored in the array, we would modify its content in finally, the fact is the return address stored in the temporary stack, only the address value pointing to a heap of change, and in the second code segment, i = 2 to the temporary presence of the stack, the finally completed when we direct the stored value i = 2 return directly.
With this knowledge later, we talk about try, catch, finally, there are several situations return statement.
The first: try {} catch () {} finally {} return;
After the statement is the order of execution in this case. (Not considered abnormal)
The second: try {return;} catch () {} finally {} return;
The case is the subject of the case have said that after executing the try block, return value will be saved in a temporary stack, and then execute the finally block, after the return value of the temporary stack.
Third: try {} catch () {return;} finally {} return;
None Exceptions: execution try, execution finally, re-execute return;
Abnormal: After performing the catch block, the value stored in the temporary return of the stack, and then execute the finally block, then return the value of the temporary stack.
Fourth: try {} catch () {} finally {return;}
Execution of a return statement finally.
Fifth: try {return;} catch () {return;} finally {};
According to whether the abnormal situation and the implementation of two or three cases.
Sixth: try {return;} catch () {} finally {return;}
After performing the try block, the return value is stored in the temporary stack, and then execute the finally block, since there are return finally, it is returned in the return value finally.
Seventh: try {} catch () {return;} finally {return;}
After performing the catch block, the return value is stored in the temporary stack, and then execute the finally block, since there are return finally, it is returned in the return value finally.
Eighth: try {return;} catch () {return;} finally {return;}
There are an exception: the implementation VII.
None Exceptions: Implementation VI.
Throws an exception: throw / throws
throws a function declaration
Declare what type of abnormality (to be thrown statement ).
throws statement: If the inside of a check method code will throw an exception (checked exception), but the method is not completely rid of himself, then you have to use javac ensure throws keyword to declare these possible exceptions thrown in the method signature, otherwise, the compiler does not pass.
throws is another way of handling abnormal, it differs from the try ... catch ... finally, throws just the abnormal function may occur in a statement to the caller while he is not a specific treatment.
The reason for this exception handling may be taken: the method itself does not know how to handle such an exception, or let the caller handle better, the caller needs to be responsible for abnormalities that may occur.
public void method name (parameter list) throws an exception list { // call the method throws an exception or: the throw new new Exception (); }
the throw - --- generated exception is thrown, an exception is thrown in action .
Usually for some kind of program logic programmer initiative throw a particular type of exception.
Immediately after the program stops after executing a throw statement; any statement after the throw is not executed,
public static void main(String[] args) { String s = "abc"; if(s.equals("abc")) { throw new NumberFormatException(); } else { System.out.println(s); } //function(); }
throw and throws the comparison
1, throws function appears in the first method; and throw appear in the function thereof.
2, throws represents a possibility of abnormal, not necessarily these anomalies occur; throw an exception is thrown, throw it must perform some kind of thrown exception object.
3, both of which are negative to handle exceptions (negative here is not that bad in this way), or possibly just throw throw an exception, but not to deal with the abnormal function, the real deal by the abnormal function Über process.
Use throws and throw keywords need to pay attention to the following points:
1.throws exception list may throw an exception may be thrown plurality of abnormality, the abnormality of the middle of each type with a comma
Method call throws an exception or 2. The method body is to throw an exception: with throw new Exception () throw in the method body in writing, said, "thrown" this action.
3. If a method called method throws an exception, you must add the try catch statement to try to catch this exception, or adding a statement, the exception is thrown to the caller to the next level of processing
Fourth, the custom exception
Use the built-in Java exception classes can be described most unusual circumstances occur during programming. In addition, users can also customize exception. User-defined exception class, just inherit Exception class can be.
Using the procedure custom exception class can be roughly divided into the following steps:
1, create a custom exception class.
2, in the method throws an exception object throw keyword.
3, if the handle exceptions in the current method throws an exception, you can use try-catch statement capture and processing; otherwise throws an exception by keyword specifies the method to be thrown to the caller in a statement of the method, proceed to the next step .
4, capture and handle exceptions in the caller unusual method.
Examples custom exception:
class MyException extends Exception { private int detail; MyException(int a){ detail = a; } public String toString(){ return "MyException ["+ detail + "]"; } } public class TestMyException{ static void compute(int a) throws MyException{ System.out.println("Called compute(" + a + ")"); if(a > 10){ throw new MyException(a); } System.out.println("Normal exit!"); } public static void main(String [] args){ try{ compute(1); compute(20); }catch(MyException me){ System.out.println("Caught " + me); } } }
reference:
https://blog.csdn.net/qq_30816657/article/details/80297646
https://blog.csdn.net/zhanaolu4821/article/details/81012382
https://www.cnblogs.com/hysum/p/7112011.html