Java Learning Note 35 (Exception)

Source: Internet
Author: User
Tags throwable try catch

The problem with the code running is the exception

Java encapsulates multiple classes of exceptions, creating exception class objects and throwing related information when a program is having problems

Anomaly System:

The Throwable class is the parent of all errors or exceptions in Java

The subclass of Throwable error class is the parent of all errors

Another subclass of Throwable exception class is the parent class of all exceptions

In development, relatively speaking, we do not care about errors, but are more concerned about exceptions

Differences between exceptions and errors (popular explanations):

Exception: the equivalent of a person with a cold, take medication to sleep and other appropriate operation can be cured, do not modify the code to deal with the exception, the program can also execute

Error: The equivalent of a person has a terminal illness, can not be cured, must modify the code, the program can execute

So it can be understood that we do not care about the terminally ill, but we will think of ways to cure those who are suffering from the disease.

Example: '

 Packagedemo; Public classDemo { Public Static voidMain (string[] args) {function1 ();    Function2 (); }     Public Static voidfunction1 () {//Exception        int[] arr = {}; System.out.println (arr[3]); //Output://Exception in thread "main" Java.lang.arrayindexoutofboundsexception:3//At Demo. Demo.function1 (demo.java:11)//At Demo. Demo.main (Demo.java:5)    }     Public Static voidfunction2 () {//Error        int[] arr =New int[666666666];        System.out.println (arr); //Output://Exception in thread "main" Java.lang.OutOfMemoryError:Java Heap space//At Demo. Demo.function2 (demo.java:19)//At Demo. Demo.main (Demo.java:6)    }}

Once the exception is thrown, the program behind it will not execute, so try to solve the problem

Keyword Throw in exception:

Write a piece of code, there is a null pointer exception

 Packagedemo; Public classExceptiondemo { Public Static voidMain (string[] args) {int[] arr =NULL;    function (arr); }     Public Static intfunctionint[] arr) {        inti =Arr[arr.length-1]; returni; }}

Add the Throw keyword to throw an exception:

 Packagedemo; Public classExceptiondemo { Public Static voidMain (string[] args)throwsException {int[] arr =NULL; inti =function (arr);    System.out.println (i); }     Public Static intfunctionint[] arr)throwsexception{//If there is an exception in the method, you need to declare it on the method: throws Exception//The thrown type and the declared exception class should be consistent//main calls this method and also needs to add a declaration        if(arr = =NULL){            //throws an exception that tells the caller//Throwing Exceptions manually            Throw NewException ("Pass array does not exist"); }        if(Arr.length = = 0){            Throw NewException ("There are no elements in the passed array"); }        inti = Arr[arr.length-1]; returni; }}/*output: Exception in thread "main" Java.lang.Exception: Pass array does not exist at demo. Exceptiondemo.function (Exceptiondemo.java:16) at demo. Exceptiondemo.main (Exceptiondemo.java:6)*/

Note here that if it is a run-time exception (RuntimeException), the throws declaration is not required,

And if this happens, then you have to change the code, otherwise the code is meaningless.

Try catch method exception handling:

 Packagedemo; Public classExceptiondemo { Public Static voidMain (string[] args) {int[] arr =NULL; Try {            inti =function (arr);        System.out.println (i); } Catch(NullPointerException ex) {System.out.println (ex); } Catch(ArrayIndexOutOfBoundsException ex) {System.out.println (ex); } System.out.println (End); }     Public Static intfunctionint[] arr)throwsNullPointerException, arrayindexoutofboundsexception {if(arr = =NULL) {            //manually throwing a null pointer exception            Throw NewNullPointerException ("Array does not exist"); }        if(Arr.length < 6) {            //manually throwing an array index out of bounds exception            Throw NewArrayIndexOutOfBoundsException ("Array has no 6 index"); }        returnArr[6]; }}/*output: java.lang.NullPointerException: Array does not exist end*/

Here, although the program has an exception, but still execute the following code, which is the exception handling

Order of Catch:

Lateral:

 package   demo;  /*   * catch handling considerations: * Sequential 
* When the exception is peer, that is, when there is no inheritance relationship, there is no order limit */ public class Exceptiondemo { public Static void main (string[] args) { try {} catch (NullPointerException e) {} CATC H (ArrayIndexOutOfBoundsException e) {}} }

Have an inheritance relationship:

 Packagedemo;//There is an inheritance relationship: The more advanced the writing in the more leaning back Public classExceptiondemo { Public Static voidMain (string[] args) {Try {                    } Catch(NullPointerException ex) {}Catch(RuntimeException ex) {}Catch(Exception ex) {}}}

Finally

 Packagedemo;//finally: must be performed//whether any exceptions will be performed Public classExceptiondemo { Public Static voidMain (string[] args) {Try{function (1); } Catch(Exception ex) {System.out.println (ex); } finally{System.out.println ("Code must execute"); }    }     Public Static voidfunctionintAthrowsException {if(A = = 0) {            Throw NewException ();    } System.out.println (a); }}//whatever you pass in, it will output: The code must execute

Precautions:

1. If the parent class throws an exception, the subclass can not throw an exception after it is overridden, but if the subclass throws an exception, the exception's inheritance cannot be greater than the parent class's exception

Custom Exceptions:

Sometimes you need a custom exception, here's an example:

 Package demo;  Public class extends runtimeexception {    public  fushuexception (String string) {        super  (string);    }      Public fushuexception () {}}
 Packagedemo;//set a story to calculate the average of two results, not a negative number//if it is a negative number, throw an exception Public classExceptiondeno { Public Static voidMain (string[] args)throwsfushuexception {Try {            inti = function (10, 97);        System.out.println (i); } Catch(Fushuexception ex) {ex.printstacktrace (); }    }     Public Static intfunctionintAintbthrowsfushuexception {if(A < 0 | | b < 0) {            Throw NewFushuexception ("Not a negative result"); }        intsum = a +b; returnSum/2; }}

Java Learning Note 35 (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.