Vi. Java Exception Handling

Source: Internet
Author: User

Directory

First, the concept of abnormal

Ii. Classification of anomalies

Third, abnormal capture and processing

Iv. Use of custom exceptions

First, the concept of abnormal

Java exceptions are a mechanism provided by Java to handle errors in the process of running a program

The so-called error refers to some unusual events that occur during the running of the program (e.g. except 0 overflow, array subscript out-of-bounds, request for read file does not exist, etc.)

A well-designed program should provide a way to handle these errors when an exception occurs, and the program will not block or produce unpredictable results because of an exception.

When an exception event occurs during the execution of a Java program, an exception class object is generated that encapsulates the information of the exception event and submits it to the Java operating system, which becomes a throw (throw) exception

When the Java runtime system accepts an exception object, it looks for code that can handle the exception and hands the current exception object to its processing, which becomes a catch (catch) exception

// An example of catching an exception  Public class Test {        publicstaticvoid  main (String args[]) {            try {                System.out.println (2/0);             Catch (ArithmeticException ae) {                System.out.print ("Error running! ");            }        }}

Ii. Classification of anomalies

Throwable: Can be thrown

Error: System errors, do not deal with their own

Exception: I can do the processing, can catch the

Runtimeexpetion: Frequent errors (such errors can be catch or not catch)

There's another kind of exception that must be captured.

Third, abnormal capture and processing
Try {    // can throw an exception to the statement catch  (SomeException1 e    ) {catch  ( SomeException2 e) {    finally  {    ...}
    • The try snippet contains code that might produce an exception
    • One or more catch code snippets after a try code snippet
    • Each catch snippet declares a specific type of exception that it can handle and provides a way to handle it
    • When an exception occurs, the program terminates the current process and executes the corresponding catch code segment based on the type of the exception being obtained
    • Finally the code of the finally segment executes at the end, regardless of whether an exception occurs

try{

    • The Try statement specifies a piece of code that is the scope for capturing and handling exceptions at once.
    • During execution, the code may produce and throw one or more types of exception objects, and the catch statements after it are handled separately for each of these exceptions.
    • If no exception is generated, all catch code snippets are skipped and not executed

} catch () {

    • In a catch statement block is the code that handles the exception, and each try statement block can accompany one or more catch statements to handle the different types of exception objects that may be produced
    • The exception object declared in the catch (catch (Someexception e)) encapsulates the information that occurs at the time of the exception, and some methods of the object can be used in the CATCH statement block to obtain the information.
    • For example: GetMessage () method: Used to get information about an exception event. Printstacktrace () Method: Used to track the contents of the execution stack when an exception event occurs.

} finally () {

    • The finally statement provides a unified exit for exception handling, which enables unified management of the program's state before the control process goes to other parts of the program
    • The Dinah specified by the finally is executed regardless of whether or not the exception is thrown in the block specified by the try.
    • Usually in the finally statement can do the cleanup of resources, such as: Close open files, delete temporary files, etc.

For some exceptions that you can't handle, or exceptions that you don't want to handle, you can throw an exception straight out so you don't have to add try{}catch{to the code snippet}

 //  An example of a thrown exception   class   test { public  static  void  Main (String        Args[]) throws   IOException {test ();  static  void  Test () throws   IOException {System.out.println ( 2/0); }}
// Another method of throwing anomalies without try...catch  Public class Test {        publicstaticvoidthrows  IOException {             int i = 0;             if (i = = 0)                {thrownew ioexception ("error");         }}}

Look at an example, this is the stack of printing information, although the error many lines, but perhaps as long as the change can be resolved:

Also, be aware of the following issues when catching exceptions:

Iv. Use of custom exceptions

Using custom exceptions generally has the following steps:

1. Declaring your own exception class by inheriting the Java.lang.Exception class

2. Generate an instance of the custom exception in the appropriate location of the method and throw it with the throw statement

3. Declare the exception that may be thrown by the method in the declaration section of the method with the throws statement

//Create a exception class to store your own exception Public classMyexpectionextendsException {Private intID;  PublicMyexpection (String message,intID) {Super(message);  This. ID =ID; }     Public intgetId () {returnID; }}
//Test Class Public classTest {//Define a method     Public voidRegist (intNumthrowsmyexpection {if(Num < 0) {            Throw NewMyexpection ("should not be negative", 3); } System.out.println ("Number of Registrants:" +num); }    //define another method     Public voidManager () {Try{regist (100); } Catch(myexpection e) {System.out.println ("Registration failed with error type Code =" +E.getid ());        E.printstacktrace (); } System.out.println ("Operation is over!" "); }    //Program Entry Main method     Public Static voidMain (string[] args) {Test T=NewTest ();    T.manager (); }}

You can debug the output yourself

Attention:

Overriding this method when the original method has an exception requires throwing an exception or non-throwing exception that is consistent with the type of exception thrown by the original method, and cannot be overridden in other cases

Vi. Java Exception Handling

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.