Java Learning (Exception class)

Source: Internet
Author: User
Tags throwable try catch

First, what is an exception:

Exceptions are problems that occur at run time. Usually described with Exception .

In Java, an exception is encapsulated into a class , and when a problem occurs, an exception class object is created and the exception-related information is thrown (such as details, names, and where the exception is located).

Second, the exception of the inheritance relationship:

The Throwable class is the superclass ( ancestor class ) of all errors and exception classes.

The Exception exception class and its subclasses are inherited from the Throwable class to represent exceptions that may occur in Java and to handle these exceptions reasonably.

The RuntimeException class is a run exception class , inherited from the exception class, and its subclasses can only exist during the run, and when present, only the source code can be modified, this exception cannot be processed .

The error Class is a class with exception that represents a serious error in Java and can only be resolved by modifying the code.

A summary of the inheritance system:

    Throwable: It is the superclass (ancestor Class)        of all errors and exceptions|-error errors         | -Exception Compile-time exception, Problems            with compiling Java programs |-runtimeexception run-time exception, problems during Java program running

Third, the difference between the exception and the error:

An exception is an exception that occurs when the program is compiled or run , and we can handle the exception in some way, and the program will stop running if the exception is not handled .

Errors are serious problems that occur at run time , cannot be handled , programs will stop running , and error is usually a system-level issue that occurs on the system where the virtual machine JVM resides, only Resolve the issue by modifying the source code .

Iv. the process of abnormal production:

1. An exception is generated when running or compiling

2. Creating an object of the exception class

3. Declaring the Exception class

4. Pass the Exception class object to the caller (main () method) processing

5. The caller cannot process and then pass the exception class object to the JVM virtual machine

6.JVM Virtual Machine Prints the information of the exception class (name, details, location of the exception) on the screen, and stops the program from running

V. Throw an exception throw

In Java, a throw keyword is provided to throw a specified exception .

How to use:

1. Create an exception object. Encapsulate some tips

2. Inform the caller of this exception

Use format:

Throw new Exception class name (parameter);

Vi. Declaration of abnormal throws

Declaring the exception format:

Modifier return value type method name (parameter) throws exception 1 name, exception 2 name {

}

Seven, catch abnormal try...catch...finally

Catch Exception: Exception-specific statements are captured in Java and can be handled in a specified manner for the exceptions that occur

Statement format:

Try {     // The statement that needs to be instrumented.  }catch// parameters.      // the processing statement for the exception.  finally  {     // The statement is bound to be executed. }

try: Write code in this code block that might produce an exception.

catch: A catch that is used to perform some kind of exception, which implements the processing of the caught exception.

finally: There are some specific code that needs to be executed, regardless of whether the exception occurs. Also, because exceptions cause program jumps, some statements do not. Finally, the problem is solved, and the code stored in the finally code block is bound to be executed.

How to combine the catch exception:

1. Try Catch finally combination: detects an exception, passes it to catch processing, and disposes of the resource in finally.

2. Try catch combination : Exception detection for the code and pass the detected exception to catch processing. The exception is captured for processing.

3. One try multiple catch combination : Exception detection of the code and passing the detected exception to catch processing. Different captures are processed for each exception information.

Note: This exception handling requires that exceptions in multiple catch cannot be the same , and if there is a child parent exception relationship between multiple exceptions in a catch, then A subclass exception is required in the catch handler above, and the parent class exception is handled in the following catch.

4. Try finally combination : Exception detection of the code, after an exception is detected because there is no catch, so the default JVM will be thrown. The exception is not captured for processing. But the function's open resource needs to be closed, all finally. Only to close the resource.

Eight, abnormal operation period runtimeexecption

Characteristics:

The run-time exception is thrown in the method definition without the throws declaration , and the caller does not have to handle the exception

    When a run-time exception occurs, the source code needs to be modified by the program personnel

Ix. exceptions in the method rewrite details

1. When a subclass overrides a parent class method, if a method of the parent class declares an exception, the subclass can only declare the parent class exception or subclass of the exception, or not declare it.

class Fu {    publicvoidthrows  runtimeexception {}}class  Extends  Fu {    publicvoidthrows runtimeexception {}  //      throws the same exception as the parent class / // throws the parent class child exception }

2. When a parent class method declares more than one exception, only a subset of the exceptions can be declared when the child class overrides

classFu { Public voidMethod ()throwsnullpointerexception, classcastexception{}}classZiextendsFu { Public voidMethod ()throwsNullPointerException, ClassCastException {}
Public voidMethod ()throwsnullpointerexception{}//throws part of the parent class exception Public voidMethod ()throwsClassCastException {}//throws part of the parent class exception}

3. When the overridden method has no exception declaration, the subclass cannot declare the exception when overridden.

class Fu {    publicvoid  method () {}}classextends  Fu {    public voidthrows Exception {}// wrong Way }

Ten, the common method of anomaly

The Throwable class provides us with a number of methods for manipulating Exception objects , which are commonly used as follows:

1.getMessage Method : Returns the details string of the exception, which is the exception prompt information

2. ToString Method : Returns the name of the exception and the details string

3. Printstacktrace: Output The name and details string of the exception in the console, the code location where the exception occurred

Xi. Custom class exceptions

Format:

extends // or inherit runtimeexception     Public exception name () {}      Public  Super(s);}}

Custom Exception Inheritance Exception Demo:

class extends exception{    /*     Why do you define a constructor because you see that there is an initialization method in the exception description class in Java that provides an exception object.     */     Public myexception () {        Super();    }      Public myexception (String message)    {        Super(message); // if the custom exception requires exception information, you can do so by calling the parent class's constructor with a string argument.     }}

Custom Exception Inheritance RuntimeException Demo:

class extends runtimeexception{    /*     Why do you define a constructor because you see that there is an initialization method in the exception description class in Java that provides an exception object.     */     myexception () {        Super();    }    MyException (String message)    {        Super(message);   If the custom exception requires exception information, you can do so by calling the parent class's constructor with a string argument.     }}

Instance code:

Use of Throw,throws,try/catch

 Packagecom.oracle.Demo01; Public classDemo01 {//try/catch format: Used to handle exceptions//try{//code being instrumented (code that may appear to be abnormal)//}catch (Exception class name variable) {//how exceptions are handled//}finally{//code that must be executed//        }     Public Static voidMain (string[] args) {int[] arr={1,2,3}; Try{            intres=GetArray (arr);        System.out.println (RES); }Catch(ArrayIndexOutOfBoundsException Ex1) {//when multi-catch processing, there is no sequencing of the lateralSystem.out.println (EX1);//when a parent-child class relationship occurs, be sure to put the subclass in frontSystem.out.println ("===========");            System.out.println (Ex1.getmessage ()); System.out.println ("===========");                    System.out.println (Ex1.tostring ()); }Catch(NullPointerException ex2) {System.out.println (EX2);            System.out.println (Ex2.getmessage ()); System.out.println ("===========");        Ex2.tostring (); }finally{System.out.println ("Code that must be executed"); } System.out.println ("Did I do it?"); }    //the difference between throw and throws is used to report exceptions.//after the throw keyword, you must follow the exception object//The throws keyword must be followed by the exception class name to pass the exception to the caller     Public Static intGetArray (int[] arr)throwsarrayindexoutofboundsexception,nullpointerexception{if(arr==NULL){            Throw NewNullPointerException ("Array is empty O (╯-╰) o"); }        if(arr.length<4){            Throw NewArrayIndexOutOfBoundsException ("The array is not long enough (? '? д?′)!"); }        intI=arr[3]*2; System.out.println ("AAA"); returni; }}

Java Learning (Exception class)

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.