Deep understanding of Java exceptions

Source: Internet
Author: User
Tags finally block throw exception

Exception structure:

    • Exception inheritance structure: Throwable is the base class, error and exception inherit throwable.
    • Runtimeexception,ioexception,sqlexception such as inheritance exception;ioerror,virtualmachineerror such as inheritance error.
    • Error and RuntimeException and their subclasses become unchecked exceptions (unchecked), and other exceptions become checked exceptions (checked).

Error exception:

Error is a subclass of Throwable that is used to indicate a serious problem that a reasonable application should not attempt to capture. In this scenario, the application can only abort the run, such as an error in the Java Virtual machine. Error is a unchecked Exception, and the compiler does not check that the error is handled and does not catch exceptions of type error in the program.

RuntimeException Exception:

Exception exceptions include runtimeexception exceptions and other non-runtimeexception exceptions.
RuntimeException is a unchecked Exception, which means that the compiler does not check whether the program handles RuntimeException and does not have to capture the runtimexception type of exception in the program. You do not have to throw the RuntimeException class in the method body declaration.
When runtimeexception occurs, there is a programming error in the program, so you should find the wrong modification program instead of capturing RuntimeException.

Checked Exception Exception:

Checked Exception exception, which is also the most used in programming Exception, all inherited from Exception and not runtimeexception the exception is Checked Exception, In the IOException and ClassNotFoundException.
The JAVA language stipulates that checked Exception must be processed, that the compiler checks for this, either declares the throw checked Exception in the method body, or captures checked Exception with a catch statement, Otherwise it cannot be compiled.

To throw an exception when declaring a method:

Syntax: Throws (a little) (method throws Exception1,exception2,.., exceptionn{})
Why do I throw an exception in declaring a method?
Method throws an exception as important as the type of the method return value. If the method throws an exception without declaring that the method throws an exception, the client programmer can call the method and not write the code that handles the exception. Then, in the event of an exception, there is no suitable exception controller to resolve the 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.

Why is the exception thrown must have been checked for exceptions?
RuntimeException and error can be generated in any code, they do not need to be shown by the programmer to throw, and in the event of an error, the corresponding exception will be automatically thrown. When encountering error, programmers are generally powerless; when encountering runtimeexception, there must be a logic error in the program, to modify the program; only checked exceptions are the programmer's concern, and the program should and should only throw or handle checked exceptions . Just checking for exceptions is thrown by programmers, in two cases: the client programmer calls the library function that throws the exception, and the client programmer throws the exception using the throw statement himself.

Note: The override method cannot throw a new exception or check an exception that is more extensive than the check exception declared by the overridden method. However, you can throw fewer, more limited, or non-throwing exceptions.

Throw an exception in the method:

Syntax: Throw (slightly):
The throw always appears in the function body and is used to throw an exception of type Throwable (throw new Exceptionname). The program terminates immediately after the throw statement, and the statement following it is not executed, and then in all the try blocks that contain it (possibly in the upper call function), look for the try block containing the catch clause that matches it.
What exception is thrown?
For an exception object, the really useful information is the object type of the exception, and the exception object itself is meaningless. For example, if the type of an exception object is ClassCastException, then the class name is the only useful information. So, when choosing what exception to throw, the key is to choose the class name of the exception that clearly describes the exception.

Try-catch-finally statement:

try {      // 可能会发生异常的程序代码  (监控区)catch (Type1 id1) {      // 捕获并处理try抛出的异常类型Type1  catch (Type2 id2) {      // 捕获并处理try抛出的异常类型Type2  finally {      // 无论是否发生异常,都将执行的语句块  }  

A pair of curly braces after the Try keyword will wrap a piece of code that may have an exception, called the monitoring area. An exception object is created when the Java method has an exception during the run. Exception is thrown outside the monitoring area;

After the exception is thrown outside the monitoring area, the Java Runtime system attempts to find a matching catch clause to catch the exception. If there is a matching catch clause, the exception handling code is run, and the Try-catch statement ends;

It is important to note that once a catch catches a matching exception type, it enters the exception handling code. Once the processing is finished, it means that the entire Try-catch statement ends. Other catch clauses no longer have an opportunity to match and catch exception types. Therefore, 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.

The finally keyword guarantees that the statements in finally will be executed regardless of whether the program leaves the try block in any way. When you need a place to execute code that must be executed under any circumstances, you can put the code in the finally block. When you want to restore resources other than memory to their initial state, you need to use the finally clause. Resources that need to be cleaned include: Files that have been opened or network connections, graphics displayed on the screen, and so on.

It is important to note that an exception cannot be thrown in a finally block. The Java exception handling mechanism guarantees that, in any case, the finally block must be executed before leaving the try block, so when an exception occurs in the try block, the Java Virtual machine first goes to the finally block to execute the code in the finally block, and after the finally block executes, Throws an exception out again. If an exception is thrown in a finally block, the exception that is caught by the try block cannot be thrown, the exception that is caught externally is the exception information in the finally block, and the real exception stack information that occurs in the try block is lost.

Execution order of try, catch, finally statement blocks:

    • When the try does not have an exception: the statement in the TRY statement block is executed by itself, the program skips the Catch statement block, executes the finally statement block, and the subsequent statement;
    • When a try exception occurs, the exception is not handled in the CATCH statement block: This exception will be thrown to the JVM for processing, and the statement in the finally statement block will still be executed, but the statement after the finally statement block will not be executed;
    • When a try exception occurs, there is a case in the catch statement block that handles this exception: in the TRY statement block, the statement after the exception is not executed, after the matching catch statement block executes, executes the statement in the finally statement block, and finally executes the statement after the final statement block;

Cite an example:

 Public classtestexception { Public testexception() {} Boolean testEx () throws Exception {Boolean ret =true;Try{ret = testEx1 (); }Catch(Exception e) {System. out. println ("testEx, catch Exception"); RET =false;ThrowE }finally{System. out. println ("TestEx, finally; return value= "+ ret);returnRet (finallyBlock does not complete normally)}} Boolean testEx1 () throws Exception {Boolean ret =true;Try{ret = testEx2 ();if(!ret) {return false; } System. out. println ("testEx1, at the end of Try");returnRet }Catch(Exception e) {System. out. println ("testEx1, catch Exception"); RET =false;ThrowE }finally{System. out. println ("testEx1, finally; return value= "+ ret);returnRet (finallyBlock does not complete normally)}} Boolean testEx2 () throws Exception {Boolean ret =true;Try{intb = A;intC for(inti =2; I >=-2;                  i--) {c = b/i; System. out. println ("i="+ i); }return true; }Catch(Exception e) {System. out. println ("testEx2, catch Exception"); RET =false;ThrowE }finally{System. out. println ("testEx2, finally; return value= "+ ret);returnRet (finallyBlock does not complete normally)}} Public Static void Main(string[] args) {TestException TestException1 =NewTestException ();Try{Testexception1.testex (); }Catch(Exception e)          {E.printstacktrace (); }      }  }

The resulting output is:
i=2
I=1
TESTEX2, catch exception
TESTEX2, finally; Return Value=false
TESTEX1, finally; Return Value=false

When the Finall block contains a return statement, Eclipse gives the warning "finally block does not complete normally" for the following reasons:

1. The finally block executes regardless of whether there is a return statement in the try block or catch block.

2. The return statement in the finally block overwrites the previous return statement (the try block, the return statement in the catch block), so if there is a return statement in the finally block, the Eclipse compiler will report a warning "finally block Does not complete normally ".

3. If the finally block contains a return statement, even if the previous catch block re-throws an exception, the statement calling the method does not get the exception that the catch block re-throws, but instead gets the return value of the finally block and does not catch the exception.

conclusion, you should avoid including the return statement in the finally block. If you include a return statement or re-throw an exception in the preceding statement, and include the return statement in the finally block, you are confusing the concept and do not understand the meaning of the finally block.

Citation information:
In-depth understanding of Java exception handling mechanisms
An in-depth study and analysis of anomalies

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Deep understanding of Java exceptions

Related Article

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.