Exception Handling in Java

Source: Internet
Author: User
Tags throw exception try catch

1: Concept of the anomaly (Exception)

Java exception when Java provides a mechanism for handling errors in a program

2: Processing mode

Java uses an object-oriented approach to handling exceptions.

    • Throw exception: If an exception occurs, the method generates an object representing the exception, stops the current execution path, and submits the exception object to the JRE
    • Catch exception: After the JRE gets the exception, it looks for the appropriate code to handle the exception, and the JRE looks in the method's call stack, starting from the generated exception method until the appropriate exception-handling code is found.

3: Exception Classification:

Many exception classes are defined in the JDK, which correspond to a variety of possible exception events, all of which are derived from an instance of the thorwable class. if the built-in exception class does not meet your needs, you can also create your own exception class

  

Error class---Do not need our---the only way: restart

Exception in Checked Exception is the compiler will check

The RuntimeException compiler does not check, for example:

1:int a = 1/0;

2: null pointer exception (NULLPOINTEREXCEPTION):, normally the object is empty

3: Array out of bounds (arrayindexoutofboundsexception)

4: Object conversion error (ClassCastException) to Judge E.g:obj instanceof

5: Number format exception (NumberFormatException)

e.g String str = "153153AG";

Integer i = new integer (str);

4: Exception handling method First: Catch exception (try Catch finally)

Try

    • A try statement must have at least one catch statement block or a finally statement block:
    • After the execution of the exception-handling code is completed, it is not returned to the try statement to execute the code that has not been executed

Catch:

    • Each try statement block can accompany one or more catch statements to handle the different types of exception objects that may be produced
    • Common methods:

ToString () Method: Displays the class name of the exception and the cause of the exception

GetMessage () Method: Displays only the cause of the exception, but does not display the class name.

Printstacktrace () Method: Used to track the contents of the stack when an exception event occurs.

--These methods are inherited from the Throwable class

    • If there is an inheritance relationship between the exception classes, it is important to note in order that the more top-level classes are placed below , then the extra catch is omitted directly.

Finally

    • It is common to close the open resources of the program block in finally, such as: file stream, release database connection, and so on.

Instance:

File operation:

    

This problem is because the file may not exist

Code:

Importjava.io.FileNotFoundException;ImportJava.io.FileReader;Importjava.io.IOException; Public classTestfilereader { Public Static voidMain (String args[]) {FileReader reader=NULL; Try{Reader=NewFileReader ("D:/lp.txt"); Charc = (Char) Reader.read (); CharC2 = (Char) Reader.read (); System.out.println ("" + C +C2); } Catch(FileNotFoundException e) {e.printstacktrace (); }        //the two catch here cannot be swapped because IOException is the parent of FileNotFoundException        Catch(IOException e) {e.printstacktrace (); } finally {            Try{reader.close (); } Catch(IOException e) {e.printstacktrace (); }        }    }}
file Operations

 Try-catch-finally-return Order of execution:

Code:

ImportJava.io.FileInputStream;Importjava.io.FileNotFoundException;Importjava.io.IOException; Public classTestfilereader { Public Static voidMain (String args[]) {string str=NewTestfilereader (). OpenFile ();    System.out.println (str); }    PrivateString OpenFile () {System.out.println ("AAA"); Try{FileInputStream fis=NewFileInputStream ("D:/lp.txt"); intA =Fis.read (); System.out.println ("BBB"); return"Step1"; } Catch(FileNotFoundException e) {System.out.println ("catching!!");            E.printstacktrace (); return"Step2"; } Catch(IOException e) {e.printstacktrace (); return"Step3"; }finally{System.out.println ("Finally"); }    }    }
no exception code

Results:

ImportJava.io.FileInputStream;Importjava.io.FileNotFoundException;Importjava.io.IOException; Public classTestfilereader { Public Static voidMain (String args[]) {string str=NewTestfilereader (). OpenFile ();    System.out.println (str); }    PrivateString OpenFile () {System.out.println ("AAA"); Try{FileInputStream fis=NewFileInputStream ("D:/wu.txt"); intA =Fis.read (); System.out.println ("BBB"); return"Step1"; } Catch(FileNotFoundException e) {System.out.println ("catching!!");            E.printstacktrace (); return"Step2"; } Catch(IOException e) {e.printstacktrace (); return"Step3"; }finally{System.out.println ("Finally"); }    }    }
there is an exception code

Results:

  

  Conclusion: 1: Execute a try catch to assign a value to the return value

2: Execute finally

3:return

5: Exception Handling method The second type: throws sentence

       

Exception Handling in Java

Related 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.