Java Basics-Exceptions

Source: Internet
Author: User
Tags throw exception throwable try catch

I. Exception anomalies

1. Overview

An exception is an error that occurs while the program is running

Exception Origin: The problem is also a specific thing in real life, can also be described in the form of Java classes. and encapsulated into objects.

In fact, Java is a description of the abnormal situation after the object.

2. Java's exception system

1. You can see that there are two sub-classes under Throwable, error and exception

For serious problems, Java is described by the error class. The error class generally does not write targeted code to handle it.

For non-critical, Java is described by the exception class. For exception, you can use a targeted processing method for processing.

This also constitutes the Java anomaly System:

Throwable

|---error//error indicates system-level errors, program cannot process

|---Exception//run-time error, the program needs to do some corresponding processing

2. The connection and difference between error and exception

1) Common denominator: both error and exception inherit from Throwable interface

2) Difference: Error indicates system-level errors, the program can not be processed, not controlled, such as Java running environment abnormal or hardware errors, insufficient memory resources, for this abnormal program can not process, only exit!

Exception represents a program-level exception that usually needs to be modified (runtime exception) or requires exception handling (checked exception).

It is due to the programmer sloppy (runtime exception) or program design so

3. Exception Exception classification

1) Runtime exception: All instances of the RuntimeException class and its subclasses are called run-time exceptions, and compilation can pass but run-time errors.

such as the divisor is 0 and array subscript out of bounds (null pointer, type conversion exception), etc., requires the programmer to modify the logic in order to run smoothly, of course, if you have processing requirements can also display capture them.

2) Compile-time exception: all non-runtimeexception system exceptions are at compile-time exceptions, Java considers that compile-time exceptions are exceptions that can be handled, so Java programs must be handled explicitly.

If the program does not handle this type of exception, You cannot compile the

3. How the JVM handles exceptions

When a function produces an exception, there are two ways of handling it:

A: Handle the problem yourself and continue running (two ways are explained below)

B: There is no handling for itself, only to the JVM that calls main (or throws exception in the Main method)

The JVM has a default exception handling mechanism that handles the exception. and the name of the exception, the exception information. The location where the exception occurred is printed on the console, and the program stops running

4. Two ways to handle exceptions

It says that you can handle exceptions yourself, and you have two ways to handle exceptions.

1) try...catch...finally format catch exception

① three formats: a) try catch B) Try catch finally C) try finally

All the other formats are wrong.

Try code to check for exceptions

Catch is used to catch exceptions

Finally to release resources

②finally Keywords:

The body of the statement that is finally controlled is bound to execute unless the JVM exits (for example, System.exit (0)) before execution to finally.

So the finally code block is used to release resources, and in IO flow operations and database operations, you will see

      The difference between the 1:final,finally and finalize of the extended surface question:

FINAL:A) Modified class: Indicates that the class will never let other classes be inherited

b) Modification method: Indicates that the method can be inherited, but cannot be overridden

c) Modifier variable: Indicates that the value of the property cannot be changed

A statement body in a finally:try statement that is bound to execute to free resources

A method in the Fanalize:object class that is called by the garbage collector to reclaim objects when the garbage collector determines that no more references to the object exist

    Note 1: The program will still run down after the exception is handled through the try catch mechanism , but the contents of the try section will not be executed again.

 Public Static void Main (string[] args) {        try{            int a = 10/0;            System.out.println ("Try code block continues execution");        } Catch (ArithmeticException e) {            System.out.println ("An exception has occurred");        }        SYSTEM.OUT.PRINTLN ("main function continues execution");    }

So the result of this code execution is: An exception occurred the main function continues execution

Note 2:try the back if with multiple catch, then small exception put front, large exception put back, according to the principle of polymorphism, if large put front

will receive all of the sub-classes, the latter will be meaningless, so will be an error

Note 3: If you define some code that must be executed in a function, you can put the code that is executed in the finally code block in the form of try{}finally{}

2) throws way to handle exception-throw exception

In the function method inside some situation, the program can not continue to run, need to jump, with throw to throw the exception object.

The difference between ①throws and throw

A:throw

* Used in the body of the method, followed by the name of the exception object

* Only one exception object name can be thrown

* Indicates thrown exception, handled by the statement in the method body

B:throws

* Used after the method declaration, followed by the exception class name

      * Can be separated by commas with multiple exception class names

* Indicates a thrown exception, handled by the caller of the method

Note: Throw throws if the Runtimeexceptin runtime exception object is thrown, the function can not be declared processed. Reason to understand

5. Precautions for unusual use

1) Special cases:

A) when a subclass overrides a parent class method, the child class's method must throw the same exception or subclass of the parent exception. (father is broken, son can not be worse than father)

b) If the parent class throws more than one exception, when the subclass overrides the parent class, it can only throw the same exception or a subset of his, the subclass cannot throw exceptions that the parent class does not have

c) If the overridden method does not throw an exception, then the subclass's method must not throw an exception, if there is an exception in the subclass method, then the subclass can only try, not throws

2) How to use exception handling

Principle: If the function can be handled within the problem, with a try, if not handled, referred to the caller, which is used throws

Difference: In a try statement block if no return method can continue execution, and throw throws an exception after the method exits

Custom exceptions are required if the JDK does not provide the corresponding exception

  

  

   

Java Basics-Exceptions

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.