Java: Exception Handling

Source: Internet
Author: User
Tags assert getmessage throw exception

The content of this article:
    • Introduction to Exceptions
    • Handling Exceptions
    • Assertion

Starting Date: 2018-03-26

Abnormal:
    • Exceptions are errors that occur during a program's operation, such as "except 0 exceptions", which can occur if a divisor is zero.
    • Exceptions can affect the normal operation of the program, so we need to handle exceptions.
    • All exception classes are subclasses that inherit from the Java.lang.Exception class. The exception class has two primary subclasses: the IOException class and the RuntimeException class.

Common exceptions:

Arithmetic Exception class: Arithmeticexecption

Null pointer exception class: NullPointerException

Type cast Exception: ClassCastException

Array subscript out-of-bounds exception: ArrayIndexOutOfBoundsException

Input/Output exception: IOException

Handling Exceptions:

    • Exception capture: try...catch...finally
      • Format:
      • Try code block: The code in which the exception can occur is placed inside
      • Catch code block "can have multiple": an action to catch an exception
        • E is the caught exception class object, and direct printing results in a string result (thread, type, location) that contains the exception
        • E.getmessage (): Returns only the type of exception + reason
        • E.printstacktrace (): Type of exception + reason + location
        • E.tostring (): Type of exception + reason
      • Finally "optional": Put code that executes whether or not an exception occurs
      • The exception class can be captured as the parent of all exception classes if the type is not determined to be accurately captured exception
      • After the exception capture succeeds, the code behind the try...catch...finally code block can execute successfully.

 Public classDemo { Public Static voidMain (string[] args) {//int a=10/0;        Try{            inta=10/0; }Catch(ArithmeticException e) {System.out.println ("Run in ArithmeticException" +e); //run in ArithmeticException java.lang.ArithmeticException:/by Zero        }        Catch(Exception e) {System.out.println (e); }finally{System.out.println ("Final Execution");//final execution of the        }    }}

    • Declaration of exception:

Throws is used to declare an exception, declaring a function that might occur. "When a throw is thrown in a function to throw an exception, the function header must declare the exception using throws"

    • Throw exception:

Throw is used to manually throw exceptions and can throw custom exception information: Throw exception type (exception information)

 Public classDemo2 {Static intDivintAintbthrowsarithmeticexception{if(b==0){            Throw NewArithmeticException ("occurred except for 0 exceptions! "); }        returnA/b; }         Public Static voidMain (String args[]) {Try{System.out.println (div (2,0)); }Catch(ArithmeticException e) {System.out.println (E.getmessage ());//exception occurred except 0! }finally{System.out.println ("in finally");//In finally} System.out.println ("After finally");//After finally            }}

In general, exception throw processing (throw throws) is generally used when you do not want to handle exceptions in a function, otherwise you use try...catch...finally to catch exceptions.

Custom Exceptions:

Sometimes we don't define the exception we want (like our MySQL connection exception), then we can customize the exception.

    • All exceptions must be subclasses of Throwable.
    • If you want to write an inspection exception class (Some of the exceptions that the compiler helps to check), you need to inherit the Exception class.
    • If you want to write a runtime exception class (exception for example, array subscript out of bounds and access null pointer exceptions), then you need to inherit the RuntimeException class " This exception class does not need to be throws".

classMyExceptionextendsexception{ Publicmyexception () {} Publicmyexception (String msg) {Super(msg); }} Public classDemo3 {Static intDivintAintbthrowsMyException {if(b==0){            Throw NewMyException ("An exception has occurred! "); }        returnA/b; }         Public Static voidMain (String args[]) {Try{System.out.println (div (2,0)); }Catch(Exception e) {System.out.println (e);//exception. MyException: There are 0 exceptions!         }            }}

Assertion:

    • Assertion (assertion) is a common debugging method in software development.
    • The assertion is generally judged whether the condition is consistent to determine whether the program continues to execute. "For example, if you want to eat, then assert your meal, or you may eat the air."
    • assertion on:Eclipse, MyEclipse assert default is off, want to turn on assert need to set perferences-"java-" installed JREs to configure the virtual machine parameters, Configured as-ea or-enableassertions
    • Assert is used in Java to define assertions: format: Assert [Boolean expression]

 Public class Demo {    publicstaticvoid  main (string[] args) {        Booleanfood = false ;        System.out.println ("Ready to start eating")        ; assert Food ;                System.out.println ("Rice has Come");}            }

Java: Exception Handling

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.