Java exception Summary

Source: Internet
Author: User
Tags finally block

1. All exceptions in java are inherited from superthrowable. Exceptions are classified into two categories: Common exceptions and errors. The corresponding class names are Exception and Error.

Common exceptions are inherited from the Exception class, which can be divided into check exceptions and non-check exceptions.

Check exception: the so-called check exception forces the program to handle all checked exceptions. It must display the handling check exception. If the program is not processed, an error will occur during compilation and cannot be translated. An exception instance that is not a RuntimeException class or its subclass is called an exception check.

Non-check exception: it is also called a running exception. Exceptions occur during running, such as null pointers, array out-of-bounds, class conversion errors, and division by 0, all non-checking exceptions are inherited from the RuntimeException class and its subclass. You can either capture or throw a display without displaying it, or capture or throw a display. The Runtime exception does not need to be explicitly thrown. If the program needs to catch the Runtime exception, you can use the try... catch Block to catch the Runtime exception.

Error: It is generally caused by problems related to Java virtual machines, such as system crashes, virtual machine errors, and dynamic link failures. Such errors cannot be recovered and captured. Generally, applications cannot handle these errors. Therefore, applications should not try to capture ERROR objects, you do not need to declare in its throws clause that this method throws any Error or its subclass. This Error will cause program interruption.

2. How to capture and throw exceptions

This is two ways to handle exceptions. When will it be thrown? When to capture? To give a simple example, the divisor may be 0, so it is necessary to perform the check. But what is the meaning of Division 0? The environment that is currently working to solve the problem may be able to clearly understand how to handle the case where the divisor is 0. However, if not, an exception should be thrown. This is a simple and general principle, but not all situations are suitable. After an exception is thrown, an exception object is created in the heap. A reference to the exception object is displayed in the current environment. At the same time, the exception handling mechanism takes over the program and finds an appropriate location to continue executing the program, the proper position is the exception handling program.

Check exceptions are applicable to recoverable situations, and non-checked exceptions are applicable to programming errors. The main principle for determining which exception to use is: if the caller is expected to be able to recover it properly, the checked exception should be used in this case. It forces the caller to handle this exception in the catch clause or spread it out. Therefore, each checked exception declared in the method is a potential reminder to the API User: this exception may be recovered.

Unchecked exceptions often identify programming errors. It is beneficial to continue execution if the program throws unchecked exceptions. If the program does not capture such a writable structure, it will cause the current thread to stop and receive an appropriate error message. Therefore, programming errors are generally indicated by runtime exceptions.

All in all, applicable to recoverable situations are checked exceptions; for program errors, applicable to runtime exceptions. Of course, black and white are not so clear. Specific programming should be analyzed in detail. For example, a running exception may be caused by a programming error or a temporary error, the API designer needs to consider whether resource depletion allows restoration.

public class DivideByZero {    public static void main(String[] args) {        try {            int c = testByZero();            System.out.println("c="+c);        } catch (Exception e) {            System.out.println("run main exception");            //e.printStackTrace();        }            }    public static int testByZero() {        int i = 10;        int j = 0;        int b = 0;        try {            b = i / j;        } catch (ArithmeticException e /*Exception e*/) {            throw e;        }        return b;    }}

Custom exception class

The class that inherits Throwable can be the parameter type of the catch clause.

Custom exceptions must inherit the Exception base class or Throwable. to customize a Runtime Exception, you must inherit the RuntimeException base class.

A custom exception class usually requires two constructors: one is a non-parameter constructor and the other is a constructor with a string, this string is used as a detailed description of the exception object (that is, the return value of the getMessage method of the exception object), and super is called to pass the string parameter to the message attribute of the exception object, the message attribute is the detailed description of the exception object.

 

Use finally to reclaim Resources

 

Note: 1: only try blocks are required. That is to say, if you do not have try blocks, you cannot have catch blocks and finally blocks;
NOTE 2: both the catch Block and finally block are optional, but at least one of the catch Block and finally block can appear at the same time;
NOTE 3: there can be multiple catch blocks. The catch Block that captures the parent exception must be behind the catch subclass exception;
NOTE 4: The try block and the finally block are not supported;
Note 5: Multiple catch blocks must be placed behind the try block and the finally block must be located behind all catch blocks.

The above two cases show that, unless the try block or catch block calls the method to exit the VM (that is, the System. exit (1);). Otherwise, no matter what code is executed in the try block or catch block, the finally block for exception handling will always be executed.

public class TestException1{    public static boolean test()    {        try        {            return true;        } finally        {            return false;        }    }    public static void main(String[] args)    {        boolean a = test();        System.out.println(a);    }}

  

Running result: false

Description of the preceding Applet: An Explain urn false statement is defined in the finally block, which will render the return true statement ineffective in the try block!

To sum up this small problem:

When a program executes a try block and catch Block encounters a return or throw statement, both statements will immediately end the method, so the system will not immediately execute these two statements, instead, find the finally block in the exception handling process. If the finally block is not found, the program immediately executes the return or throw statement to terminate the process. If a finally block exists, the system immediately starts to execute the finally block. The system will jump back to execute the return or throw statement in the try block or catch block only after the finally block is executed, if the finally block also uses statements that cause method termination, such as return or throw, the finally block has terminated the method and does not need to jump back to execute any code in the try block or catch block.

To sum up, try to avoid statements that cause method termination by using return or throw in the finally block. Otherwise, some strange situations may occur!

Throws an exception

The idea of throwing an exception using throws is: the current method does not know how to handle this type of exception. The exception should be handled by the upper-level caller, if the main method does not know how to handle this type of exception, you can also use the throws declaration to throw an exception, which will be handled by the JVM.

How does JVM handle exceptions: prints information about the exception tracing stack and terminates the program running. Therefore, many programs automatically end when an exception occurs.

When throws is used to declare that an exception is thrown, there is a restriction: it is a rule of "two small" during method Rewriting: the exception type thrown by the subclass method declaration should be the subclass or equal of the exception type thrown by the parent class method declaration. The subclass method cannot throw more exceptions than the parent class method declaration. That is, if the exception thrown by the subclass is the parent class of the exception thrown by the parent class, the program cannot be compiled.

Because the Checked exception has some inconveniences, in most cases, you can use a Runtime exception. If the program needs to capture exceptions in a suitable place and handle the exceptions, the program can also use try... catch a Runtime exception.

Throw an exception

1. when the exception thrown by the throw statement is a Checked exception, the throw statement is either explicitly caught in the try block or put in a method with throws declaration and throw, that is, the exception is handed over to the method caller for handling.

2. when the exception thrown by the throw statement is a Runtime exception, the statement does not need to be placed in the try block or in a method with throws declaration. The program can explicitly use try... catch to catch and handle the exception. You can ignore the exception and submit the exception to the method caller for handling.

Public class TestException3 {public static void throwChecked (int a) throws Exception {if (a <0) {/*** throws Exception on its own. The code must be in the try block, or in a method with throws Declaration */throw new Exception ("the value of a is greater than 0 and does not meet the requirements");} public static void throwRuntime (int) {if (a <0) {/*** throws a RuntimeException automatically. This exception can be caught explicitly or ignored completely, handle this exception to the method caller */throw new RuntimeException ("the value of a is greater than 0 and does not meet the requirements");} else {System. out. println ("a value:" + a) ;}} public static void main (String [] args) {try {/*** a method with throws declaration is called here, and this exception must be caught (use try... otherwise, the main method should be declared again and throw */throwChecked (-3);} catch (Exception e) {System. out. println (e. getMessage ();} throwRuntime (3 );}}

  

However, in practical applications, more complex processing methods are often required. In the current method of exception occurrence, the program only partially handles the exception, some operations can be completed only by the caller of the method. Therefore, an exception should be thrown again so that the caller of the method can capture the exception.

To handle the same exception in collaboration with multiple methods, you can use throw in the catch Block.

Public class TestException4 {// The following AuctionException is a custom exception class private double initPrice = 30.0; public void bid (String bidPrice) throws AuctionException {double d = 0.0; try {d = Double. parseDouble (bidPrice);} catch (Exception e) {e. printStackTrace (); throw new AuctionException ("the bid price must be a numerical value and cannot contain other characters! ");} If (initPrice> d) {throw new AuctionException (" the bidding price is lower than the starting price and is not allowed! ");} InitPrice = d;} public static void main (String [] args) {TestException4 ta = new TestException4 (); try {ta. bid ("df");} catch (AuctionException AE) {// TODO: handle exception System. err. println (AE. getMessage ());}}}

 

 

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.