Java Exception handling mechanism

Source: Internet
Author: User
Tags getmessage throwable

Exceptions allow us to force the program to stop running and tell us what's wrong, or force the program to handle the problem and return to a stable state.

Java provides a Throwable class, which is a superclass of all exceptions and error classes. Only if the object is an instance of this class can it be thrown through a Java virtual machine or a Java throw statement. Structure diagram for the Throwable class and its subclasses:

First, the type of exception

Error: Generally refers to serious system errors, virtual machine-related problems, such as system crashes, virtual machine error, dynamic link failure, etc., this type of error is generally not fixed or impossible to capture, will lead to application interruption.

Exception: Refers to some of the anomalies that can be captured and may be recovered, such as an array subscript out of bounds arrayindexoutofboundsexception, the number is 0 apart from the exception arithmeticexception, Input and output exception IOException.

You can know that error is the burden of the JVM, RuntimeException class is the responsibility of the program should be burden, the exception is the responsibility of the application of the specific burden. As programmers are concerned about is exception.

1. Non-inspected exception

Refers to the compiler does not require a forced disposition of the exception, usually programming logic error, is the programmer should be avoided, the RuntimeException class and his subclass are non-inspected exceptions, as follows:

1) Wrong type conversion: classcastexception

2) group subscript out of bounds: arrayindexoutofboundsexception

3) NULL pointer access exception: NullPointerException

4) exception generated by 0: ArithmeticException

2, inspected the exception

The compiler requires exceptions that must be disposed of, and general exceptions caused by external factors when the program is run, as follows:

1) No class exception was found for the specified name: classnotfoundexception

2) access to non-existent file exceptions: FileNotFoundException

3) Operation file exception: IOException

4) An exception occurred while manipulating the database: SQLException

Java requires the Java program to catch or declare all the exceptions that are being inspected, and for such exceptions, if the program does not process it, it will result in unexpected results, rather than having to do anything with the exception that is being inspected.

Second, catch the exception statement

  1. Try......catch......finally ...

The try selects the scope to catch the exception, and when executed, the code inside the parentheses after the catch produces the exception object and throws it, and then uses the catch block to handle the exception.

Finally, the block of statements to be executed regardless of whether an exception occurred, such as the shutdown of the database. Note: If there is a definite return statement in the TRY statement block, finally will always be executed before the return.

  2, throws and throw

Throw: The statement explicitly throws an exception that must be a throwable class, or new to create an instance: throw new Xxexception ();

After the throw statement is executed, the next statement that the run process will immediately stop the throw will also pause execution.

Throws: If a method a can throw an exception, and he does not handle the exception itself, then the a method must throw the exception to the calling method so that the program can continue execution. Usage: Method () throws Exception1,exception2,. That is, throws is used to declare all exceptions that a method might throw, and if a method declares a inspected exception, the class that calls the method must handle the exception. You can use Try......catch ... Throws can also be declared on this method.

public static void Main (string[] args) {        //TODO auto-generated method Stub        int number = 0;        try {            System.out.println ("aaaaaaaa");            Number = Integer.parseint (Args[0]);            System.out.println ("bbbbbbbb");        } catch (Exception e) {            //Todo:handle Exception            throw new ArrayIndexOutOfBoundsException ("Out of Bounds");            SYSTEM.OUT.PRINTLN ("illegal numbers");        }        finally{            System.out.println ("The number you entered is:" +number);        }    }

Results:

Aaaaaaaa

The number you entered is: 0

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:out of bounds

At Com.wt.others.ThrowTest.main (throwtest.java:12)

Principle: But throwing an exception will use new to create an exception object on the heap, then your execution path is terminated, and a reference to the exception object is ejected from the current environment, and the exception handling mechanism takes over the program and begins to find an appropriate place to execute the program, the proper place is the exception handler, Its task is to recover the program from the error state.

public static void Main (string[] args) {        testthrows (args);    }    public static void Testthrows (string[] tmp) {        try {            createthrows (tmp)        } catch (Exception e) {            //Todo:ha Ndle exception            System.out.println ("Come from Createthrows");        }    }    public static void Test2throws (string[] tmp) throws Exception {        createthrows (TMP);    }    public static void Createthrows (string[] tmp) {        int num = 0;        num = Integer.parseint (tmp[0]);        System.out.println ("The number you entered is:" +num);    }

Throws and throw can be used together to throw an explicit exception to the caller after catching the exception.

The difference between the two:

throw is used in the method, throws is used after the method signature, When using these in the same place, it is important to note that throws throws an exception of the type range that is larger than the throw.

public static void Main (string[] args) {        try {            MethodA ()        } catch (Exception e)  {            //Todo:handle Exce Ption            System.out.println (E.getmessage ());        }        MethodB ();    }    public static void MethodA () {        try {            System.out.println ("Come in A");            throw new RuntimeException ("manufacturing exception");        } Finally  {            //Todo:handle exception            System.out.println ("finally" with a);}    }    public static void MethodB () {        try {            System.out.println ("Come in B");            return;  This returns, after executing the finally statement, returns        } finally  {            //Todo:handle exception            System.out.println ("Finally with B" );        }    }

Results:

Come in A

With the finally of a

Manufacturing exceptions

Come in B

With the finally of B

  3, GetMessage and Printstacktrace methods

GetMessage: Returns the detailed message string for this Throwable object

Printstacktrace: Output This Throwable object and its trace to the standard error stream

try{fun    ();} catch (Exception e) {    e.getmessage (e);   E.printstacktrace (e);}

Third, custom exception class

Exception is generally chosen as the parent class, as follows:

public class MyException extends exception{public    myexception () {        super ();    }    Public myexception (String msg) {        super (msg);    }    Public myexception (Throwable cause) {        super (cause);    }    Public myexception (String msg,throwable cause) {        Super (MSG, cause);}    }

  

In fact, not all exceptions need to be handled, exception handling will occupy a certain amount of resources, affecting the execution efficiency of the program. Carefully observe the name and line number of the exception, minimize the volume of the Try statement block, when handling the exception should be printed out the stack information of the exception to facilitate debugging use.

Cleanup of exception objects does not require much care because they are built on the heap with new, and the garbage collector automatically cleans them out.

Java Exception handling mechanism

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.