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 are the ways to handle Java exceptions

2025-04-08 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces the relevant knowledge of "what are the ways to handle Java exceptions". The editor shows you the operation process through actual cases, which is simple, fast and practical. I hope this article "what are the ways to handle Java exceptions" can help you solve the problem.

What is an anomaly?

Exceptions are particularly common when we write code, because programmers spend most of their time fixing bug, and in java they can be divided into two through the throwable top-level class, one is Error (error) and the other is Exception (exception).

Error: Error differs from exceptions in that errors cannot be handled, but problems caused by programmers, such as syntax errors, which require programmers to check their own syntax, such as result errors (StackOverflowError and OutOfMemoryError)

That requires the programmer to check his logic

Exception (exception): this can be handled in some ways, such as throws (declare exception) and try {} catch {} (handle exception), which are all the ways we handle exceptions, and exceptions are divided into checked exceptions (compile-time exceptions) and unchecked exceptions (run-time exception RuntimeException).

Compile-time exception: a program cannot be compiled, which is a compile-time exception. For example, when clone, an exception must be declared through throws.

Run-time exception: means that the program can be compiled, but an exception occurs at run time. For example: NullPointerException,

ArrayIndexOutOfBoundsException 、 ArithmeticException .

We can handle all the above exceptions, but the error requires the programmer to check the code himself.

Exception handling

We have two ways to deal with it:

One is defensive in advance:

Boolean ret = false

Ret = log in to the game ()

If (! ret) {

Deal with login game error

Return

} r

Et = start matching ()

If (! ret) {

Handling matching errors

Return

} r

Et = Game confirmation ()

If (! ret) {

Handling game confirmation errors

Return

} r

Et = Select Hero ()

If (! ret) {

Deal with the error of choosing a hero

Return

} r

Et = load game screen ()

If (! ret) {

Handle loading game errors

Return

}.

.

The defensive type in advance is to check whether there is an error at every step. this disadvantage is that the code appears to be very chaotic and inefficient.

One is to admit mistakes afterwards:

Try {

Login to the game ()

Start matching ()

Game confirmation ()

Select Hero ()

Load the game screen ()

...

} catch (login game exception) {

Handle login game exception

} catch (start matching exception) {

Processing start matching exception

} catch (game confirmation exception) {

Handle game confirmation exception

} catch (Select Hero exception) {

Handle selected hero exception

} catch (load game screen exception) {

Handle the exception of loading game screen

}.

....

This practice is to put all possible exceptions in the code in the try, and if you find that the exception is being caught, it is the first operation to deal with problems encountered.

We often use the second trycatch to make the code concise, clear, and more efficient.

Exception thrown

If a piece of code does not meet your expectations, we will throw an exception in this code. In java, we use the keyword throw to throw an exception.

The syntax is the throw new exception (the exception you want to throw)

Public class TestDemo {public static void func (int a) {if (aversion 10) {throw new RuntimeException ("axioms 10 does not meet expectations, throw this exception");}} public static void main (String [] args) {func (10);}}

Look at this code: for example, the number 10 does not meet the expectations of our program, so to throw an exception, we can run out like this: throw new RuntimeException ("axiomatic 10 does not meet expectations, throw this exception")

Handling exceptions

We usually have two ways to handle exceptions, one is to declare exceptions through throws, the other is to check whether there are any exceptions in the code block through try {} catch {} through try, catch if there is an exception catch, and normal the following code if there are no exceptions.

Throws declared exception

Syntax: throws exception, exception, exception. (multiple exceptions can be declared)

Public class TestDemo {public static void function (int [] array) {System.out.println (array [] args) {int [] array = {7,8,9,5,6}; function (array);}}

As we all know, visiting the 100 subscript here is an array out of bounds exception:

Next, declare the exception through throws:

It will still make a mistake.

When we also declare an exception to the main function:

The answer will still be wrong.

So we draw a conclusion from this: throws simply tells the compiler that this exception may occur in this method, only declares it, but does not handle the exception. We can also find that if an exception occurs in a method, we will see if the method handles the exception, and if not, check to see if the upper caller has handled the exception. Here, func just declares the exception and does not handle the exception, and then the upper-level caller handles the exception (that is, the main method) or not, and finally leaves it to JVM to handle the termination program. The declared exception must be a subclass of Exception or Exception.

So how to handle exceptions? Then we will handle the exception through the try {} catch that we will talk about next.

Catch exception

Try {

} catch () {

}

At Java we use try {} catch {} to handle exceptions

Syntax:

Try {/ / Code where an exception may occur} catch (exception variable) {/ / for example: ArrayIndexOutOfBoundsException (exception to be caught) e (variable) / / if the code in try throws an exception, the exception type captured by catch here is the same as the exception type thrown in try, / / or when the base class of the exception is thrown in try, it will be caught / / a pair of exceptions can be handled normally After the processing is completed, jump out of the try-catch structure and continue to execute the post-order code} finally {/ / the code will be executed here, which is used for resource cleaning and other work.

Let's talk about try {} catch () {} first.

/ * handle exceptions in the method * / public class TestDemo {public static void function (int [] array) throws ArrayIndexOutOfBoundsException {try {System.out.println (array [100]);} catch (ArrayIndexOutOfBoundsException e) {System.out.println ("array [100]-> array subscript out of bounds exception catch- > catch successful") }} public static void main (String [] args) throws ArrayIndexOutOfBoundsException {int [] array = {7,8,9,5,6}; function (array);}} / * handling exceptions in main methods * / public class TestDemo {public static void function (int [] array) throws ArrayIndexOutOfBoundsException {System.out.println (array [100]) } public static void main (String [] args) throws ArrayIndexOutOfBoundsException {int [] array = {7,8,9,5,6}; try {function (array);} catch (ArrayIndexOutOfBoundsException e) {System.out.println ("array [100]-> array subscript out of bounds exception catch- > capture successful");}

We can handle exceptions using try {} catch () {}, either in the method or in the main method. Although throws is of no use here, it can clearly tell the programmer that this exception may occur in the future, so it is still necessary.

Try {} catch {} Note 1:

When the capture exception succeeds, the subsequent business code executes normally, but it will not execute if it is not captured.

Try {} catch {} Note 2:

Try {} catch {} Note 3:

Throws just declares the exception and does not handle the exception. We handle the exception through try {} catch () {}.

Try {} catch {} Note 4:

When the exception type caught by catch does not match the type of exception that occurred, it will not be caught, so it continues to throw the exception until the JVM receives it and terminates the program.

Try {} catch {} Note 5:

When multiple exceptions occur, it is necessary to catch multiple catch, multiple exceptions, multiple times.

Try {} catch {} Note point 6:

Since the Exception class is the parent class of the corresponding exception class, can you catch Exception, that is, multiple exceptions, once?

When catch performs type matching, it not only matches the exception objects of the same type, but also captures the subclass objects of the target exception type.

The answer is no. Because when contemporary code is complex, only capturing the Exception class doesn't know what went wrong.

Print exception information

We can also use printStackTrace to print error messages.

Finally:

Finally is often used with try {} catch () {}. Finally is mainly used to clean up resources, clean up, and finally must be executed.

Let's take a look at the result of such a piece of code.

Public class TestDemo {public static int function (int [] array) throws ArrayIndexOutOfBoundsException {try {System.out.println (array [100]);} catch (ArrayIndexOutOfBoundsException e) {System.out.println ("array [100]-> array subscript out of bounds exception catch- > capture successful"); return-1 } finally {System.out.println ("finally is mainly used for cleaning up resource recovery and cleaning ~"); return 9;} public static void main (String [] args) throws ArrayIndexOutOfBoundsException,ArithmeticException {int [] array = {7,8,9,5,6}; System.out.println (function (array)) System.out.println ("following is the business code ~");}}

The answer is not the return-1 we want, the end of the execution, but the return9, which we can understand here as the 9 of finally overwriting the-1 in catch. So the code in finally is bound to be executed.

Exception handling flow

My understanding:

The first step is to check whether there are any exceptions in the code in try. If there is any exception, catch will catch it. If there is no exception, go on. Here, if catch does not catch it, check whether the upper caller has handled it. If so, handle it. If there is no handling, give it to the JVM termination program. If the catch captures it, the following normal business code executes normally. Finally, the code in the catch executes regardless of whether the finally catches the exception or not.

Official:

The program executes the code in try first.

If there is an exception in the code in try, it ends the code in try to see if it matches the exception type in catch.

If a matching exception type is found, the code in catch is executed

If no matching exception type is found, the exception is passed up to the upper caller.

Whether a matching exception type is found or not, the code in finally is executed (before the end of the method).

If the upper-level caller does not handle the exception, it continues to pass upward.

Until the main method does not have the appropriate code to handle the exception, it will be handed over to JVM to handle it, and the program will terminate abnormally.

Custom exception

When we are working on a very large project, we will find that there are no built-in exceptions in Java, so we need to define an exception ourselves to maintain the exceptions we actually encounter.

Although there are plenty of exception classes in java, they can not fully represent some exceptions encountered in actual development. At this time, we need to maintain the exception structure that conforms to our actual situation.

Declaring an exception yourself in Java does not mean that you write the name of an exception as an exception, but that the exception you define needs to inherit the original built-in exception.

We use a login code to explain custom exceptions:

Class LogIn {private String name = "Admin"; / / username private String password= "CsDn1263987..0"; public void logInFor (String name,String password) throws UserNameErrorExecption, PasswordErrorException {if (! this.name.equals (name)) {throw new UserNameErrorExecption ("username parameter exception!") ;} if (! this.password.equals (password)) {throw new PasswordErrorException ("user password parameter exception!!") ;} System.out.println ("~ ~ login succeeded ~ ~");}} public class TestDemo {public static void main (String [] args) throws UserNameErrorExecption, PasswordErrorException {LogIn logIn = new LogIn (); / / logIn.logInFor ("Admin", "CsDn1263987..0"); try {logIn.logInFor ("Admin", "CsDn126398..0") } catch (UserNameErrorExecption nameError) {nameError.printStackTrace (); System.out.println ("wrong user name!") ;} catch (PasswordErrorException passwordError) {passwordError.printStackTrace (); System.out.println ("wrong password!") ;}

Custom exception:

Class PasswordError extends Exception {public PasswordError (String message) {super (message);}} class UserNameError extends Exception {public UserNameError (String message) {super (message);}}

These are the two exceptions we define.

Define two exceptions by inheriting from Exception.

Generally speaking, we want to inherit Exception or RunTimeException for custom exceptions, and we can also define other exceptions.

Custom exceptions usually inherit from Exception or RuntimeException

Exceptions inherited from Exception are checked by default

Exceptions inherited from RuntimeException are unchecked by default

This is the end of the content about "what are the ways to handle Java exceptions". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.

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