Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the method of handling JAVA exceptions?

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "what is the way to handle JAVA exceptions". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what is the way to handle JAVA exceptions".

1:try-catch

Structure:

* structure:

* try {

* exception de snippet may occur

*} catch (possible exception) {

* solution

*}

Order:

* order of execution of try-catch:

* 1. Execute the code block in the try block if an exception occurs

* 2. Match the exception type declared in catch through the exception that occurs

* 3. If the match succeeds and executes the code block in the catch, if the match fails, jvm handles the current exception information (the termination program outputs the exception information)

* 4. Continue to execute the remaining code

Example:

Public class Test04 {

Public static void main (String [] args) {

Try {

Int num = 1ax ArithmeticException new ArithmeticException ()

System.out.println (num)

} catch (InputMismatchException e) {/ / InputMismatchException e = new ArithmeticException ()

System.out.println ("Divisor cannot be 0")

}

System.out.println ("hey hey")

}

}

Matters needing attention

PS: only one exception can be handled.

2Rank-multiple catch

Structure:

* structure:

* try {

* Code that may have an exception

*} catch (exception type 1 E1) {

* solution 1

*} catch (exception type 2 e2) {

* solution 2

*} catch (exception type 3 e3) {

* solution 3

*}. {

*}

Sequence

* order of execution:

* 1. Execute try block if there is an exception

* 2. Match the exceptions declared in multiple catch

* 3. If the match succeeds, the current catch block that matches successfully is executed. Continue to execute the following code after the execution of the try-catch block.

* 4. If the match fails, the jvm handler will terminate the output of the exception information.

* 5. In general, we will add Exception to the last catch to obtain exception information that may not have been captured.

Examples

Public class Test05 {

Public static void main (String [] args) {

Scanner input = new Scanner (System.in)

Try {

System.out.println ("Please enter the divisor->")

Int num1 = input.nextInt ()

System.out.println ("Please enter divisor->")

Int num2 = input.nextInt ()

System.out.println (num1+ "/" + num2+ "=" + (num1/num2))

} catch (InputMismatchException e) {/ / there is no reason for maintaining the exception in this exception object, so the exception information null value cannot be obtained through getMessage

/ / e.printStackTrace ()

System.out.println (e.getMessage ())

System.out.println ("incorrect user input")

} catch (ArithmeticException e) {/ / the cause of the exception is maintained in the exception object, so the exception information can be obtained through getMessage

System.out.println (e.getMessage ()); / / by zero

System.out.println ("Divisor cannot be 0")

} catch (Exception e) {/ / Exception e = new possible exception (); parent variable points to subclass object

/ / Polymorphism

System.out.println (e.getMessage ())

System.out.println ("the alien took the page. Please wait.")

}

}

}

Note:

PS:

In general, we add Exception to the last catch to get exception information that may not have been caught.

Methods in common exception objects:

* Common methods in exceptions:

* e.getMessage ()-- > get the cause of exception flouting

* e.printStackTrace ()-- > print the number of lines in which the exception occurs and the fully qualified name of the exception * e.toString-- > the fully qualified name of the exception

3Rich-multiple catch-finally

Structure:

* structure:

* try {

* Code that may have an exception

*} catch (exception type 1 E1) {

* solution 1

*} catch (exception type 2 e2) {

* solution 2

*} catch (exception type 3 e3) {

* solution 3

*}. {

*} finally {

* Code block

*}

Order:

* order of execution:

* 1. Execute try block if there is an exception

* 2. Match the exceptions declared in multiple catch

* 3. If the match succeeds, execute the catch block that matches successfully. Execute the finally code block try-catch-finally block and continue to execute the following code.

* 4. If the match fails and the jvm handler terminates the output exception information, the finally code block will be executed.

* 5. In general, we will add Exception to the last catch to obtain exception information that may not have been captured.

* 6. Generally use finally to close the connection resources.

Example:

Public class Test06 {

Public static void main (String [] args) {

Scanner input = null

Try {

Input = new Scanner (System.in)

System.out.println ("Please enter the divisor->")

Int num1 = input.nextInt ()

System.out.println ("Please enter divisor->")

Int num2 = input.nextInt ()

System.exit (0); / / shut down the virtual machine 0 exit normally non-0 forced exit

System.out.println (num1+ "/" + num2+ "=" + (num1/num2))

} catch (InputMismatchException e) {

System.out.println ("incorrect user input")

} catch (ArithmeticException e) {

System.out.println ("Divisor cannot be 0")

} catch (Exception e) {

System.out.println ("the alien took the page. Please wait.")

} finally {

System.out.println ("I was executed")

/ / closed here

Input.close ()

}

}

}

Note:

PS:

Finally is bound to be executed with return and finally code is executed with exceptions or under normal circumstances

System.exit (number) exit virtual machine 0 normal non-0 force

4:throws declares an exception

Syntax format:

* Note the format:

* method () throws exception type 1, exception type 2. {}

Note:

S Don't forget that one method can declare multiple exception information

If a method declares an exception, the caller must resolve the current exception. Solution:

A, try-catch B, continue to declare

Case study:

Public class Test08 {

Public static void main (String [] args) throws Exception {

/ * try {

/ / 1. Call the add method

Add (1 dint 2)

} catch (Exception e) {

} * /

System.out.println (add (1cm43))

}

/ *

* calculate the addition of two numbers

* an exception may occur when calling this method

* this method must declare an exception to the outside

, /

Public static int add (int num1,int num2) throws Exception {

Return num1+num2

}

}

5:throw throws exception information

Syntax format:

Throw new exception type ()

PS: throwing an exception is written inside the method

Note:

Throw throws an exception in the method body.

Generally used with throws

Case study:

Public class Test09 {

Public static void main (String [] args) {

/ / 1. Create a user object

User u = new User ()

/ / 2. Resolve exceptions

Try {

U.setGender (12); / / new Exception ()

} catch (Exception e) {

E.printStackTrace ()

}

}

}

Class User {

Private int gender

Public User () {

/ / TODO Auto-generated constructor stub

}

Public int getGender () {

Return gender

}

Public void setGender (int gender) throws Exception {

/ / determine the value of gender

If (gender==0 | | gender==1) {

This.gender = gender

} else {

/ / throw an exception

Throw new Exception ()

}

}

}

6: custom exception:

To customize an exception:

* how to customize exceptions:

* 1. Create a class so that the current class inherits either Exception or RuntimeException

* 2. Write the constructor of the current class:

* a, be sure to write an empty constructor

Be sure to write a constructor with a description of the cause of the exception (a constructor with a String parameter)

* 3. Call the constructor of the parent class through super () inside the constructor

Custom exception how to obtain exception information: class diagram:

Example:

Public class GenderException extends Exception {

Public GenderException () {

}

Public GenderException (String str) {

Super (str)

}

}

Test class:

Public class Test11 {

Public static void main (String [] args) {

/ / 1. Create a Person object

Person p = new Person ()

Try {

P.setGender (10)

} catch (GenderException e) {

System.out.println (e.getMessage ())

}

System.out.println (p.getGender () = 0? "Girls": "Boys")

}

}

Class Person {

Private int gender

Public Person () {

/ / TODO Auto-generated constructor stub

}

Public int getGender () {

Return gender

}

Public void setGender (int gender) throws GenderException,NullPointerException {

If (gender==0 | | gender==1) {

This.gender = gender

} else {

/ / throw an exception

Throw new GenderException ("gender assignment error")

}

}

}

PS: when int is an attribute, it has a default value, which is 0. 0. And this value may lead to unstable factors during the running of the program.

Thank you for your reading. the above is the content of "what is JAVA exception handling". After the study of this article, I believe you have a deeper understanding of what JAVA exception handling is, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report