Java exception handling mechanism--in-depth understanding and application development

Source: Internet
Author: User
Tags finally block throw exception

  This article is the original blog post, strictly prohibited reprint, infringement must investigate!

Java exception handling mechanism is used frequently in daily development, its most important is just a few keywords: try, catch, finally, throw, throws, and a variety of exception. This article mainly on the basis of the use of methods, further analysis in the development of how to use the anomaly mechanism more reasonable.

    • Try-catch-finally

The use of try-catch-finally blocks is relatively simple and the frequency is the highest. The TRY block contains statements that may have an exception (which, of course, is a man-made decision, a try can theoretically contain any code), the catch block is responsible for capturing the possible exceptions, and finally is responsible for executing the statements that must be executed, where the code is executed regardless of whether an exception occurred.

For this part, because it is very basic, so make a few more key suggestions:

1, when you write Try-catch statement, the brain is to know what kind of exception to deal with, do not just in case, add a catch (Exception e), it is meaningless. Also, there may be multiple exceptions in a try block, and for each class of exceptions, write a catch to capture them separately.

2, for possible exception of the statement to Try-catch, large segment of the code Try-catch will be very detrimental to maintain the code when the location of the exception may occur, for sure not to occur the stability of the code, do not need to put in the try block.

3, Try-catch Although in function, can become the tool of process control, achieve the effect of conditional branch. However, compared to the If-else statement, Java's exception handling mechanism is based on object-oriented thinking, the use of the process requires more time and space overhead, so do not use the exception mechanism to do the basic condition judgment, only when the program will be interrupted because of the exception to capture and processing.

4. Never write the return statement in the finally block, because the finally block is always last executed, and he changes the return value expected in the try and catch blocks (for example, you catch an exception in the catch and throw e, and return in the finally statement True so that the exception you throw is "gone" because the execution of the current function has changed from throwing an exception to return true. In addition, when using resource objects and stream objects, the finally block must close the resource object, stream object.

    • Java Exception Architecture

    The base class for the Java exception System is throwable, which has two subclasses: Error and Exception. Its structure is as follows:

      

, error refers to errors that cannot be handled by the program, and refers to more serious errors inside the system. Most of these errors have nothing to do with developers, and our main concern is exception.

Exception is divided into two main blocks: Runtime exceptions and non-runtime exceptions. RuntimeException and its subclasses are called run-time exceptions, except that all exception subclass exceptions are non-runtime exceptions.

Run-time exception multiple refers to the program logic problems (that is, we write code logic problem), common errors include classcastexception: Type conversion exception, NullPointerException: null pointer exception, Indexoutofboundsexception: Out-of-bounds exception ... These exceptions can be handled by the program logic to avoid (such as adding a judgment statement to determine whether it is out of bounds, whether it belongs to a certain type, whether it is null), so the compiler put these tasks to the programmer to control, at compile time even if manually throw a run-time exception does not go to capture, the compiler will pass. Thus this type of exception is also called "Unchecked Exception" (uncheck). Also belongs to the unchecked exception and all the error. That is, all blue boxes indicate that the exception is not checked, and the Orange box indicates "Check for exceptions." For a check exception, the Try-catch block is used to capture and process the possible exception, and if it is not processed, it is thrown to the upper call until it is processed.

    • Throw and throws

The throws keyword is primarily used in method signatures to declare exceptions that might be thrown by the method. Throws can be understood to be a notification behavior, there is no actual throw exception action, but only to tell the call to his upper function, here may throw this exception;

Throw is used in a function body statement to represent the actual action that throws an actual exception, and if it is not captured and processed within the function, it will be thrown upward until it is thrown by main ()/thread.run ().

When a function throws declares that a function may throw a non-runtime exception (checking for an exception), the upper function that calls it must contain the code that handles the exception, even if the function does not show the use of throw inside. As an example:

 Public class Main {    publicstaticvoid  main (string[] args) {        exceptiontest ();    }     Static int throws IOException {                return 0;        }}

The Exceptiontest function declaration called in the preceding code throws a IOException that is a check exception, even if the exceptiontest function cannot throw the exception, and the function that invokes it must also capture the exception. Now there is no related processing logic in the main function, so it compiles errors, such as:

The exception to the runtime is another case:

1  Public classMain {2 3      Public Static voidMain (string[] args) {4 5         inti = dividetest (0);6 System.out.println (i);7     }8     Static intDividetest (intbthrowsArithmeticException {9         Ten         inti = 5/b; One         returni;  A     } -}

Also in the main function does not handle the logic of the exception, this time the declaration throws the exception is arithmeicexception, he belongs to the runtime exception (runtimeexception), so the compiler to throw aside the declaration:

Although the compilation period passes, at run time the program will still automatically throw a run-time exception and throw it up to the main function. The main thread terminates because there is no capture processing for the exception in main ().

Conclusion: My current understanding is that throws a run-time exception is meaningless unless you do so in order to follow a uniform specification. The significance of the existence of throws is mainly to give the compiler the possibility of non-runtime exceptions, so that the compiler can supervise the developers to capture and handle these exceptions.

In addition, when you need to customize an exception, if you need to check in the compilation period, and in the upper layer of uniform processing, then the direct inheritance of exception becomes a check exception, if you do not need compile-time check, throw an exception to indicate that the program exception requires a direct interrupt, Then inheriting runtimeexception becomes a run-time exception.

Java exception handling mechanism--in-depth understanding and application development

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.