java--exception

Source: Internet
Author: User
Tags array length throw exception throwable try catch

The problem with Java code that occurs during runtime is an exception. in the In Java, the exception information is encapsulated into a class. When a problem occurs, an exception class object is created and information about the exception is thrown (such as where the exception occurred, why, and so on).

Note:

1, do not use throws, with try. Catch.. Statement

2. Try: Catch.. The code below the exception code in the try scope will not execute, but try: Catch.. Statement the following code will continue to execute

3, RuntimeException exception and its subclasses do not have to be processed, the method definition does not need throws declaration, Once the run-time exception occurs , the source code needs to be modified by the program personnel.

First, the abnormal inheritance system

in the The exception class is used in Java to describe exceptions.

Throwable is the superclass of all errors or exceptions in the Java language, the ancestor class.

There is an error with exception exception, which is a subclass of Throwable, which is used to represent a serious error that may occur in a Java program. There is only one solution, modify the code to avoid error errors.

Summarize:

1 Error: 2     (1) error: The programmer can not handle, can only modify the code 3     (2) Exception exception: processing, where the runtimeexception do not handle

Differences between anomalies and errors

Exception : Refers to an exception that occurred during the compilation and operation of the program (xxxexception), we can deal with the exception in detail. If you do not handle the exception, the program will end running.

Cases:

 public  static  void   main (string[] args) { int  [] arr = new  int  [2 0 3]);  //  System.out.println ("over"); //  This code does not execute } 
because the above code has an exception

Error : Refers to an error occurred during the operation of the program (xxxerror), error errors are usually not handled in a specific way, and the program will end up running. Error errors occur at the system level and are fed back to the JVM by the system in which the JVM (the Java Virtual machine) resides. We can only fix the code for processing.

Cases:

 Public Static void Main (string[] args) {intnewint[1024*1024*100]; // This sentence runs with a memory overflow error outofmemoryerror, which opens up an oversized array space, causing the JVM to exceed the JVM's memory space when allocating array space, directly resulting in an error. }

analysis of the generation process of abnormal

run the following program before the program produces an array index out-of-bounds exception Arrayindexofboundsexception. We use diagrams to parse the process of abnormal generation.

Tool class:

class arraytools{// Gets the element by a given corner tag for the given array.  publicstaticint getelement (int[] arr,int  index)    {         int element = Arr[index];         return element;}}

Test class:

class ExceptionDemo2 {    publicstaticvoid  main (string[] args)     {         int [] arr = {34,12,67};         int num = arraytools.getelement (arr,4)        System.out.println ("num=" +num);        System.out.println ("over");}    }

Diagram of the above program execution process:

Four , throw exception throw and declare exception throws

in Java, a throw keyword is provided that is used to throw a specified exception object. So, how does throwing an exception work?

1, create an exception object. Encapsulates some hint information (the information can be written yourself).

2, the exception object needs to be told to the caller. How to Tell? How do you pass this exception object to the caller? You can do this by using the keyword throw. Throw exception object; Throw is used within a method to throw an exception object, pass the exception object to the caller, and end the execution of the current method.

Use format:

Throw new Exception class name (parameter);

For example:

Throw New NullPointerException ("The ARR array to access does not exist"); Throw New ArrayIndexOutOfBoundsException ("The index does not exist in the array, is out of range");

The following is the exception class The construction method of ArrayIndexOutOfBoundsException and NullPointerException

declaration: Identify the problem and report it to the caller. If a compile-time exception is thrown through a throw in a method without capturing processing (which is explained later), it must be declared by throws to be handled by the caller.

Declaring the exception format:

throws Exception class name 1, exception class name 2 ... {   }

V. catching abnormal try...catch...finally

To capture the exception format:

   try{       may occur exception code    }catch (Exception object ex) {Handle statement}finally{regardless of the statement that the       exception must be executed when the statement is       normally written to release the Resource    }

For example:

 Public Static voidMain (string[] args) {int[] arr=NULL; //Once an exception occurs in try, the following code in the try range will not execute        Try{            intindex=get (arr);        SYSTEM.OUT.PRINTLN (index); }Catch(NullPointerException ex) {System.out.println (ex); }Catch(ArrayIndexOutOfBoundsException ex) {System.out.println (ex); }finally{System.out.println ("This is a statement that is bound to be executed."); }    }     Public Static intGetint[] arr) throws nullpointerexception,arrayindexoutofboundsexception{if(arr==NULL){            Throw NewNullPointerException ("Array is empty"); }        if(arr.length<4){            Throw NewArrayIndexOutOfBoundsException ("Array length is not enough"); }        returnArr[3]+1; }}

Vi. combination of try...catch...finally exception handling

(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 of the code, and the detection of the exception passed 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 the catch, the subclass exception requires the catch to be handled above, and the parent exception is handled in the following catch.

(4) Try finally combination: Exception detection of the code, after detecting an exception 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.

Seven, abnormal operation period

RuntimeException and all of his subclass exceptions are run-time exceptions. Nullpointerexception,arrayindexoutofboundsexception, etc. are all run-time anomalies.

characteristics of abnormal operation period :

1, the method throws the run-time exception , the method definition does not need throws declaration, the caller does not need to handle this exception

2. If the abnormal operation period occurs , the program personnel will need to modify the source code.

Viii. exceptions in the method rewrite details

1 . When a subclass overrides a parent class method, if the 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.

  For example:  class   Fu { public   void  method () throws   RuntimeException {}}  class  Zi extends   Fu { public  void  Method () throws  RuntimeException {} //  throws the same exception as the parent class  // public void Method () throws nullpointerexception{}  //  Throw the parent class child exception } 

2. When a parent class method declares more than one exception, the subclass overrides only a subset of the exceptions.

For example: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

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

Example: The following situation exists in the parent class, which is also the case for interfaces

Problem: An exception was not declared in the interface, and an exception occurred while implementing the subclass override method.

A: You cannot make a throws declaration, only catch captures. What if the problem can't be dealt with? The catch continues to throw, but the exception can only be converted to the RuntimeException subclass thrown.

InterfaceInter { Public Abstract voidmethod ();}classZiImplementsInter { Public voidMethod () {//cannot declare throws Exception        int[] arr =NULL; if(arr = =NULL) {            //can only capture processing            Try{Throw NewException ("Buddy, you define the array arr is empty!")");}Catch(Exception e) {System.out.println ("no exception thrown in the parent method, Exception exception cannot be thrown in subclasses"); //we throw the exception object E, using the RuntimeException exception method        Throw NewRuntimeException (e); }}}

Nine, the common method of anomaly

in the The Throwable class provides us with a number of ways to manipulate exception objects:

That

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

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

3. GetMessage method: Returns the exception prompt information

Ten, custom exceptions

1. Definition of custom Exception class

Format:

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

(1) 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.     }}

(2) 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.     }}

to summarize, the constructor throws this Noageexception is inheriting exception? Or do you inherit the runtimeexception?

Inheritance Exception, it is necessary to throws the declaration, a declaration tells the caller to capture, and once the problem has been handled the caller's program will continue to execute.

Inheritance Runtimeexcpetion, throws declaration is not required, and the call does not need to write the capture code, because the call does not know the problem at all. Once noageexception occurs, the caller program will stop, and the JVM will display the information to the screen, allowing the caller to see the problem and fix the code.

java--exception

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.