Java study notes 35 (exception) and java study notes 35

Source: Internet
Author: User
Tags try catch

Java study notes 35 (exception) and java study notes 35

An exception occurs when the code is running.

Java encapsulates multiple exceptions into multiple classes. When a program encounters a problem, it creates an exception class object and throws related information.

 

Exception system:

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

The Error class, a subclass of Throwable, is the parent class of all errors.

Another subclass of Throwable Exception class is the parent class of all exceptions.

During development, we do not care about errors, but exceptions.

Differences between exceptions and errors ):

Exception: it is equivalent to a person who has caught a cold, takes medicine, sleeps, and performs corresponding operations to recover, without modifying the code to handle the exception, the program can also execute

Error: it is equivalent to a person suffering from a critical illness and cannot be cured. The program can be executed only by modifying the code.

So we can understand it as follows: We don't care about people with critical diseases, but will try to cure people with minor Diseases.

Example :'

Package demo; public class Demo {public static void main (String [] args) {function1 (); function2 ();} public static void function1 () {// exception int [] arr = {1, 2}; 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 void function2 () {// 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 an exception is thrown, the subsequent programs will not be executed. Therefore, we need to solve this problem.

 

Keyword throw in the exception:

Write a piece of code. a null pointer exception exists.

package demo;public class ExceptionDemo {    public static void main(String[] args) {        int [] arr = null;        function(arr);    }    public static int function(int[] arr){        int i = arr[arr.length-1];        return i;    }}

When the throw keyword is added, an exception is thrown:

Package demo; public class ExceptionDemo {public static void main (String [] args) throws Exception {int [] arr = null; int I = function (arr); System. out. println (I);} public static int function (int [] arr) throws Exception {// if there is an Exception in the method, declare it on the method: throws Exception // The thrown type should be consistent with the declared Exception class // main calls this method, and the declaration if (arr = null) also needs to be added {// throws an Exception, notify the caller // manually throw an Exception throw new Exception ("the passed array does not exist");} if (arr. length = 0) {throw new Exception ("no element in the passed array");} int I = arr [arr. length-1]; return I ;}/ * output: Exception in thread "main" java. lang. exception: The passed array does not exist at demo. predictiondemo. function (ExceptionDemo. java: 16) at demo. predictiondemo. main (ExceptionDemo. java: 6 )*/

Note,If it is a runtime exception (RuntimeException), throws declaration is not required,

If this exception occurs, you must modify the code. Otherwise, the code is meaningless.

 

Try catch method exception handling:

Package demo; public class ExceptionDemo {public static void main (String [] args) {int [] arr = null; try {int I = 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 int function (int [] arr) throws NullPointerException, ArrayIndexOutOfBoundsException {if (arr = null) {// manually throw a null pointer exception throw new NullPointerException ("the array does not exist");} if (arr. length <6) {// manually throw the array index out-of-bounds exception throw new ArrayIndexOutOfBoundsException ("the array does not have 6 indexes");} return arr [6] ;}/ * output: java. lang. nullPointerException: the array does not exist */

It is found that although the program has an exception, it still executes the code below, which is exception handling.

 

Catch sequence:

Level:

Package demo;/** catch handling considerations: * ordered
* When an exception is at a level, that is, there is no inheritance relationship, there is no order limit */public class ExceptionDemo {public static void main (String [] args) {try {} catch (NullPointerException e) {} catch (ArrayIndexOutOfBoundsException e ){}}}

There is an inheritance relationship:

Package demo; // There is an inheritance relationship: the more advanced the code is written, the more backward the public class ExceptionDemo {public static void main (String [] args) {try {} catch (NullPointerException ex) {} catch (RuntimeException ex) {} catch (Exception ex ){}}}

 

 

Finally:

Package demo; // finally: It must be executed // If any exception occurs, public class ExceptionDemo {public static void main (String [] args) {try {function (1 );} catch (Exception ex) {System. out. println (ex);} finally {System. out. println ("code must be executed") ;}} public static void function (int a) throws Exception {if (a = 0) {throw new Exception ();} System. out. println (a) ;}// whatever the input, the output is: the Code must be executed.

 

Note:

1. If the parent class method throws an exception, the subclass can not throw an exception after rewriting. However, if the subclass wants to throw an exception, the inheritance relationship of this exception cannot be greater than the exception of the parent class.

 

Custom exception:

Sometimes some custom exceptions are required. Here is an example:

package demo;public class FuShuException extends RuntimeException {    public FuShuException(String string){        super(string);    }    public FuShuException(){}}
Package demo; // set a scenario to calculate the average number of two-way scores, which cannot be negative. // if it is a negative number, the public class ExceptionDeno {public static void main (String [] args) throws FuShuException {try {int I = function (10, 97); System. out. println (I);} catch (FuShuException ex) {ex. printStackTrace () ;}} public static int function (int a, int B) throws FuShuException {if (a <0 | B <0) {throw new FuShuException ("the score is not negative");} int sum = a + B; return sum/2 ;}}

 

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.