In-depth understanding of Java exception Handling mechanism (general article)

Source: Internet
Author: User
Tags arithmetic operators throw exception throwable

Opening

1. Exception handling (Exception handling):

is a kind of mechanism to solve this problem, can better deal with the situation that the program can't run normally.

2. Exceptions (Exception):

is an error that may occur at run time that causes the program to terminate. This error cannot be checked out by the compilation system.

3. Common exceptions are as follows:

(1) Insufficient system resources.  For example, there is not enough memory to request memory space dynamically, there is not enough disk space to open a new output file, and so on. (2) User operation error results in incorrect operator relationship. For example, a denominator of 0 appears. Mathematical operations overflow, array out of bounds, parameter types can not be converted and so on.   4. Exception Example: in C + +, use the try, throw, catch three keywords to implement exception handling. The compound statement after the try is called the protected segment, and the code for the protected segment is likely to have an exception, so exception detection occurs in the Try section. If an exception is detected, the exception is thrown through the throw statement. Exceptions can also be detected and thrown in functions called by protected segments. The thrown exception can be an integer, a string, a variable, or even an object of a class.  In other words, there are different types of exceptions. The catch section's role is to catch exceptions and handle exceptions. In parentheses after each catch, you specify an "exception type" that indicates what type of exception it can catch.  Once an exception is caught, it is handled by an exception-handling statement.    There are two types of program execution: (1) No exception:try--> protected statement--other statements.  (2) There is an exception:tyr--> the protected statement-->throw Exception-->catch--> exception handling statement.    When writing a program with exception handling, it is also important to note that: (1) The TRY statement block and the catch statement block are a whole, and there can be no other statements between the two. (2) There can be more than one catch statement behind a try statement block, however. You cannot use a catch statement after several try statement blocks. 5. Exceptions in the program

Have a question???? Then the remaining 5 lines of code will be executed????

By visible, the remaining 5 lines of code will not be executed, then the problem comes again!!! How can we get our code done????

Use the exception handling mechanism in Java!!!

So what is the exception handling mechanism??

Can let the program in the event of an exception, according to the code pre-set exception handling logic, targeted handling of exceptions, so that the program back to normal and continue to execute

One: All exceptions and errors of the parent class--throwable

The Throwable class is the top-level parent of a Java exception type, and an object is only an instance of the Throwable class, and he is an exception object that can be identified by the exception handling mechanism. Some common exception classes are built into the JDK, and we can also customize exceptions

Depending on the compiler's processing requirements for exceptions, exceptions fall into two categories:

01. Runtime Exceptions: Exceptions generated during running in the program!

02. Check for Exceptions: exceptions generated during program compilation!

Second: The use of unusual

1. Use of exceptions

Exception handling is divided into two types: (5 keywords)

01. Using Try...catch...finally

02. Throwing Exceptions and throws declaration exceptions with throw

Use of 2.try

The code in the 01.try block where an exception might occur:

02.try cannot be used alone and must be used in conjunction with one of the catch or finally.

03. If you finish executing the try and no exception occurs, then execute the finally code block and the code after finally;

04. If an exception occurs, try to match the catch code block of the corresponding exception

Use of 3.catch

01. Each catch block is used to catch and handle a specific exception, or subclass of this exception type.

The parentheses behind the catch define the exception type and exception parameters.

03. If the exception matches and is first matched, the virtual machine will use this catch block to handle the exception.

04. You can write multiple catch code blocks! Order must be from small to large by exception type!

05. In the catch block, you can use exception parameters to get information about the exception. The exception parameter is a local variable in this catch block that cannot be accessed by other blocks.

06. If the exception that occurs in the current try block is not captured in any subsequent catch, then the first execution of the finally

07. If no exception occurs in the try, all catch blocks are ignored.

Multiple exceptions can be declared in a catch in 08.java7

Use of 4.finally

01. The finally code block executes regardless of whether the exception occurs;

02. If return is present in the try code block, then return after executing the finally code block;

03. System.exit (int status) is encountered and no finally code block is executed

System.exit (0): normal exit

System.exit (1 or not 0): Abnormal exit, typically placed in a catch code block

04. Mainly perform some cleanup work, such as closing the stream, releasing the database connection resources ...

5.try.. Catch.. Finally comprehensive attention point

01. The variables in each code block are local variables, other blocks of code cannot be accessed;

02.try cannot be used alone and must be used in conjunction with catch or finally;

03.catch code blocks can have multiple, the writing order must be based on the inheritance of the exception type from small to large writing;

04. If a return is present in a try code block, it is also executed finally before the return

6. Unusual use of small cases

Demand:
01. Let the user enter two numbers separately
02. Two-digit quotient
03. Use the exception handling mechanism to resolve any anomalies that may occur

Analysis Requirements:

01. Input Digital ===== "input stream scanner class

02. Business ===== Using arithmetic operators

03. Handling Exceptions Using try...catch...finally

       Scanner input = new Scanner (system.in);        try {            System.out.println ("Please enter the first number:");            int num = Input.nextint ();            System.out.println ("Please enter a second number:");            int num2 = Input.nextint ();            SYSTEM.OUT.PRINTLN ("Result:" + (NUM/NUM2));        } catch (ArithmeticException e) {            System.out.println ("divisor cannot be 0");            E.printstacktrace ();        } catch (Inputmismatchexception e) {            e.printstacktrace ();        } finally {            System.out.println ("End! ");        }
III: Use of throw and throws

1. Exception-Thrown categories

01. system automatically throws exception
We do not use exception handling mechanism, the system defaults to encountering exceptions when throwing exceptions!

02. Writing a statement throws an exception
Throws an exception using throw, throws declares the exception

Use of 2.throw

Grammar:

Throw new Exception type ([exception prompt statement]);

Note the point:
01. The exception type can be exception or its subclasses;

02. A throw statement can only throw an exception;

03.throw statements can only be present in the method body

04. There are two ways to solve the exception thrown by THORW
001. Handling exceptions using try...catch...finally code blocks
002. Declare the exception with throws and tell the caller

Use of 2.throws

Grammar:
Method name throws Exception type 1, exception type 2;

Note the point:
01.thows declaration after the method name;

02.throws can declare multiple exception types, separating each type with a ' comma ';

The 03.throws declaration indicates that the current method can not handle the exception, but is handled by the caller of the method;

04. If you declare an exception using throws in the main function, the JVM handles the exception!

Four: The use of abnormal chain 1. What is an anomaly chain???

  

Car a rear-ended the car B,

Car B Rear-end the car c.

Excuse me:

Who does the car C pay for?

Find the driver of car b compensation, that culprit car a driver?!

The exception chain is the wrapping of the caught exception in a new exception, and the information for the original exception is recorded in the new exception. and re-throw the exception handling mode.

Benefit: It's easy to find the root cause of the anomaly.

V: Custom exception

Considerations for Custom Exceptions:

1. The exception class must be a subclass of throwsable

2. Define the checked exception and suggest inheriting exception

3. Define run exception, suggest inherit RuntimeException

VI: Precautions for using exceptions

1. The principle of the use of exceptions

01. Exceptions can only be used in abnormal situations

02. Provide documentation for exceptions

03. Avoid exceptions as much as possible, especially at run-time exceptions

04. Maintaining Abnormal Atomicity

05. Avoid too large try code blocks

06. Specify the specific exception type in the catch

07. Do not ignore the caught exception in the catch block

In-depth understanding of Java exception Handling mechanism (general 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.