Java must know: An explanation of the exception mechanism

Source: Internet
Author: User
Tags array length finally block getmessage stack trace throw exception throwable

I. Overview of Java Exceptions
In Java, all events can be described by the class, and exceptions in Java are described by the exception class under the Java.lang package.

1, Throwable (can throw): The ultimate parent class of the exception class, it has two subclasses, error and exception.
Common methods in Throwable are:
Getcause (): Returns the reason that the exception was thrown. If cause does not exist or is unknown, NULL is returned.
Getmeage (): Returns the message information for the exception.
Printstacktrace (): The stack trace of the object is output to the error output stream as the value of the field System.err.

Hundred Cattle Information Technology Bainiu.ltd organized and published in the blog Park

2 Error (Error): Indicates that the program can not handle errors, generally unrelated to the execution of the programmer's operation. In theory, these errors are not allowed to occur, and should not be attempted through the program, so error is not a Try-catch object, and the JVM typically handles terminating the thread where the error occurred. Common subclasses of the error class have Virtualmachineerror and Awterror.

3. Virtualmachineerror (virtual machine error): Indicates that a virtual machine error has occurred.
In the Java runtime memory, the virtual machine stack, heap, and method area except the program counter will throw OutOfMemoryError when the requested memory is not satisfied;
Stackoverflowerror is thrown if the thread requests a stack depth that exceeds the allowed depth of the virtual machine.

4, Awterror (AWT component error): This error is not very common. But to mention the difference between AWT and swing , AWT is an abstract window tool using graphical functions in the operating system, written in c\c++, in order to achieve the Java "One compile, run everywhere" concept, AWT uses the intersection of various operating system graphics functions, so the function is poor, But the running speed is faster, suitable for embedded Java;
The swing component is a graphical interface system based on AWT, which is written in plain Java, so it is necessary to "compile once, run everywhere", but it is slower than AWT and is suitable for PC use.

5, Exception (Exception): The cause depends on the program, so the program should also be handled through Try-catch.
Exceptions fall into two categories: exceptions can be checked and non-checked.

exceptions can be checked : Compiler requirements must be processed, otherwise it cannot be compiled, using Try-catch capture or throws thrown. Common IOException (IO errors) and their subclasses eofexcption (file ended exception), FileNotFound (file not found exception).

Non-check exceptions (also known as runtime Exceptions): The compilation period is not checked, so it is not processed in the program, but if it does, it will be thrown at run time. So this kind of anomaly should be avoided as far as possible! Common non-checked exceptions are the RuntimeException class and its subclasses.

1 ' nullpointerexception: null pointer exception. Thrown when a nonexistent object or an object that is not instantiated or initialized is called, such as when attempting to manipulate a property, method of an empty object (assigned null).

(Instantiation: A popular understanding is to open up space for an object so that it can be called within a defined range.) Note: User u; This is just an object declaration and is not instantiated or initialized.
Initialize: The base data Type field in the instantiated object is assigned a default value or set value, NULL is assigned to the non-primitive type, and only once for the static field. )

2 ' arithmeticexception: Arithmetic condition is abnormal. The most common is that 0 is thrown when the divisor is used.

3 ' classnotfoundexception: Class not found exception. When a class is obtained by Reflection Class.forName ("Class name"), an exception is thrown if it is not found.

4 ' arrayindexoutofboundsexception: array index out of bounds exception. Thrown when an attempt is made to manipulate an array whose index value is negative or greater than or equal to the array size.

5 ' negativearraysizeexception: The array length is a negative value exception. Typically thrown when the array size is initialized to a negative value.

6 ' arraystoreexception: Array type mismatch value exception. For example, when an object array is added to an integer object with a String object, the type mismatch is thrown.

7 ' illegalargumentexception: illegal parameter exception. Thrown when a parameter value is passed out when the Java class library method is used.

second, exception handling
Exception handling Principles in Java: You must declare an exception to be thrown or catch a check exception, allowing you to ignore the error and the non-check exception.

PublicClass TestException {public static void main (string[] args) throws ioexception{//throw to check IO exception //throw is an exception thrown against an object, throws is an exception thrown for a method FileWriter FileWriter =  "output.txt"); String str = null; //str object uninitialized try {filewriter.write (str); //attempt to invoke an uninitialized str object throws a null pointer exception} catch (NullPointerException e) {System.out.println ( "Catch nullpointerexception!");} finally{str =  "finally!"; filewriter.write (str); Filewriter.close (); } }} 
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

Execution Result:
Console:

Catch nullpointerexception!

Output.txt:

finally!

1,throws meaning to throw, as long as an exception occurs, the corresponding exception object will be created, and then record the abnormal state of the operation of the exception information, delivery to the runtime system processing. Throwing an exception is certain to execute before capturing, without throwing it there will be no catch. A program can explicitly use throws to declare a thrown exception to be compiled.

2. Try-catch-finally Exception Capture statement:
In try is a program segment that can occur abnormally;

catch In order to write the corresponding exception handler method, when the exception is thrown, by the runtime system in the stack from the current position, and then back to the method, until the appropriate exception handling method is found, if not found, then execute finally or directly end the program run.

finally : The statements in the finally block are executed regardless of whether the exception is caught or handled.
Note (very important, interview frequently asked): When a return statement is encountered in a try block or catch block, the finally statement block is executed before the method returns.
In the following 4 special cases, the finally block is not executed:
1) An exception was thrown in the finally statement block and is not processed.
2) exit the program with System.exit () in the previous code.
3) The thread on which the program is located dies.
4) The CPU is turned off abnormally.

3. Execution sequence of try-catch-finally
1 ' When there is no exception capture, the catch is skipped and the finally block is executed directly.

PublicClass TestException {Publicstatic void main (String[] args) { Span class= "Hljs-keyword" >try {system. Out.println ( "Hello world! "); } catch (NullPointerException e) {system. Out.println ( "Catch nullpointerexception!");} catch (ArithmeticException e) {system. Out.println ( "Catch arithmeticexception!");} catch (Exception e) {system. Out.println ( "Catch other exception!");} finally{system. Out.println ( "finally!");}}          
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

Output Result:

Hello world!
finally!

2 ' throws an exception from the JVM when a run-time exception is thrown and no corresponding exception-handling method is defined.

public class TestException {    public static void main(String[] args){ String str = null; int a = 2, b = 0; //调用空对象的方法,会抛出空指针异常 System.out.println(str.length()); }}
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

Output Result:

Exception in thread "main" java.lang.NullPointerException
At Java interview. Testexception.main (Testexception.java:11)

3. When try catches an exception, there are cases in the catch statement block that handle this exception: in the TRY statement block is executed in order, when the execution to a statement exception, the program will jump to the catch statement block, and match the catch statement block one by one, find the corresponding handler, The other catch statement blocks will not be executed, and the statement after the exception is not executed in the TRY statement block, after the catch statement block executes, the last statement after the finally statement block is executed.

PublicClass TestException {PublicStaticvoidMain (string[] args) {String str =Nullint a =2, B =0;try {Calling an empty object method throws a null pointer exception to System.out.println (Str.length ()); //statement 1 //divisor of 0, will throw mathematical error system. "a/b=" + A/b); //statement 2} catch (NullPointerException e) {system. Out.println ( "Catch nullpointerexception!");} catch (ArithmeticException e) {system. Out.println ( "Catch arithmeticexception!");} catch (Exception e) {system. Out.println ( "Catch other exception!");} finally{system. Out.println ( "finally!");}}          
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21st

Output Result:

Catch nullpointerexception!
finally!

Iii. Customizing an exception class
Implemented by inheriting the exception class.

class MyException extends Exception { // 创建自定义异常类 String message; // 定义String类型变量 public MyException(String ErrorMessagr) { // 父类方法 message = ErrorMessagr; } public String getMessage() { // 覆盖getMessage()方法 return message; } } 
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

Iv. abnormal chain and abnormal stack trajectory

public class TestException {    public static void main(String[] args){ TestException test = new TestException(); String str = null; test.printStringMessage(str); } public void printStringMessage(String str){ System.out.println(str.length()); }}
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

Exception in thread "main" java.lang.NullPointerException
At Java interview. Testexception.printstringmessage (testexception.java:16)
At Java interview. Testexception.main (Testexception.java:12)

General Exceptions : There are Java-defined exceptions that do not require exception declarations and are defaulted to the main () method without being try-catch.

abnormal bubbling upload mechanism : When an exception object is produced, it bubbles up to the call hierarchy (usually the method's call hierarchy) until it is try-catch processed, or escalated to the main () method.

//自定义的异常类public class MyException extends Exception{ String message; // 定义String类型变量 public MyException(String ErrorMessagr) { // 父类方法 message = ErrorMessagr; } public String getMessage() { // 覆盖getMessage()方法 return message; } } 
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
Testing the anomaly chain, bubbling mechanismPublicClass TestException {void Firstthrow () throws MyException {Throws the custom exception System.Out.println ("Oringinally creat a myexception and throw it Out");ThrowNew MyException ("MyException");//True Throw exception} void Secondthrow () throws MyException {//throws custom Exception FirstThrow () ; //call Firstthrow ()} public testexception () throws MyException {//constructor method, throws a custom exception Secondthrow (); //call Secondthrow ()} public static void main (string[] args) {try{//Call construction method TestException Testexception=new testexception ();} catch (myexception e) {e.printstacktrace (); System. out.println ( "Catch a My Exception!");}}    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21st
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

Output Result:

Oringinally creat a myexception and throw it out
Java interview. myexception:myexception
At Java interview. Testexception.firstthrow (Testexception.java:11)
At Java interview. Testexception.secondthrow (testexception.java:16)
At Java interview. TestException. (TESTEXCEPTION.JAVA:20)
At Java interview. Testexception.main (testexception.java:26)
Catch a My exception!

The record information from the exception stack can be found in the exception throwing mechanism and order corresponding to the code:

Firstthrow () generates MyException object----the exception that bubbles to call its secondthrow (), bubbles to the testexceptionchain that calls Secondthrow (). The main () method that bubbles to printtry.

Notice that the exception object has been thrown until it is try-catch captured in the Printtry Mian () Method!

Java must know: An explanation of the exception 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.