Java Exception Handling

Source: Internet
Author: User

Structure of exception handling

try{    Possible exception statement    }[catch (Exception type Object) {    //exception handling}][catch (Exception type Object) {    //exception handling}][catch (Exception    type Object) {// Perform exception handling}][finally]{    The statement to execute regardless of whether an exception occurred}

Case: Writing a simple exception

 Public class test{    publicstaticvoid  main (String args[]) {        System.out.println ( "perform calculations");         Try {            System.out.println (10/0);        } Catch (ArithmeticException e) {            e.printstacktrace (); // How to perform an abnormal output         }        System.out.println ("End of calculation");}    }

Run results

Calculation java.lang.ArithmeticException:/by zero at        Test.main (test.java:6) End of calculation

Throwable is the parent class for all exceptions, with error, and exception

Error: Refers to the JVM exception, at this time the program has not been executed;

Exception: Refers to the exception that occurs during program operation

Throws keywords:

When the program has an exception to the call processing, and the call must be handled with exception

classmathutil{ Public Static intDivintXinty) throws exception{returnx/y; }} Public classtest{ Public Static voidMain (String args[]) {Try{System. out. println (Mathutil.div (Ten,2));//due to the existence of throws, exception handling is required here}Catch(Exception e) {e.printstacktrace (); }    }}

When a method throws an exception through throws, it must be processed by using try{}catch{} at the time of invocation, and if you continue to throw an exception on the main method, the exception is given to the JVM for processing.

Throw keyword: Throw can proactively throw an exception and then use try{}catch{} for processing

 Public class test{    publicstaticvoid  main (String args[]) {        try {            thrownew Exception ("Custom Exception");        } Catch (Exception e) {            e.printstacktrace ();     }}}

The difference between throws and throw

Throw: Refers to an artificially thrown exception in a method that can be defined by itself or by a system-defined exception

Throws: Refers to the exception that is thrown when the method definition is defined, and must be handled abnormally when the method is called.

Example: A simple exception code model

classmymath{ Public Static intDivintXintYthrowsexception{//throwing an exception here is given to the call processingSYSTEM.OUT.PRINTLN ("Calculation Start"); intresult = x/y; System.out.println ("End of calculation"); returnresult; }} Public classtest{ Public Static voidMain (String args[]) {Try{Mymath.div (10,0);//there is an exception here and you want the following statement to continue, you need to handle the X/Y statement in the MyMath class}Catch(Exception e) {e.printstacktrace (); }    }}

Execution results

Calculation start Java.lang.ArithmeticException:/by zero at        Mymath.div (test.java:5) at        Test.main (test.java:13)

After an exception occurs, the subsequent statement is no longer executed, and the code is not conducive to the operation of the program

Example: improving the above procedure

classmymath{ Public Static intDivintXintYthrowsexception{//throwing an exception here is given to the call processing        intresult = 0; System.out.println ("Calculate Start"); Try{result= x/y;//If an exception occurs, this phrase is not executed}Catch(Exception e) {ThrowE//throws an exception to the method, because there is throws in the method, the throw throws an exception to the used processing}finally{//indicates whether or not an exception occursSystem.out.println ("End of calculation"); }        returnresult; }} Public classtest{ Public Static voidMain (String args[]) {Try{Mymath.div (10,0);//there is an exception here and you want the following statement to continue, you need to handle the X/Y statement in the MyMath class}Catch(Exception e) {e.printstacktrace (); }    }}
Calculation start calculation end Java.lang.ArithmeticException:/by zero at        Mymath.div (test.java:6) at        Test.main (test.java:18)

RuntimeException class

If the RuntimeException class or subclass exception is thrown through throws on the method, the user can choose to handle it as needed, and if the user does not process it, it is given to the JVM for processing.

Ask? Differences between the exception and RuntimeException classes;

Exception is the parent class of runtimeexception, throws throws exception exception the user must handle, runtimeexception can selectively handle

RuntimeException Common subclasses: Nullpointerexception,classcastexception arithmeticexception

Assert keyword (assertion)

Two forms of

1. an assert Boolean expression;

2. Assert Boolean expression : Basic type/Expression/object type; This is similar to the three-mesh operator .

You need to manually enable the assertion feature when you are compiling the program

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.