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 java exception handling method?

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

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

This article mainly introduces "what is the java exception handling method". In the daily operation, I believe that many people have doubts about what the java exception handling method is. The editor consulted all kinds of data and sorted out a simple and easy-to-use operation method. I hope it will be helpful to answer the doubt of "what is the java exception handling method?" Next, please follow the editor to study!

Exception introduction

Let's take a look at several common types of exceptions in the previous figure.

All exceptions come from Throwable. Throwable has two subclasses, Error and Exception.

Error usually indicates serious errors, which are not recommended to be catch.

Note that there is an exception, such as ThreadDeath is also inherited from Error, but it represents the death of a thread, although it is not a serious exception, but because applications do not usually catch such exceptions, they are also classified as Error.

Exception represents the exception that the application wants catch to live in.

There is a very special exception in Exception called RuntimeException. RuntimeException is called a run-time exception, and it doesn't need to be displayed in catch, so it's also called unchecked Exception. Other non-RuntimeException Exception needs to display try catch, so it is also called checked Exception.

Don't ignore checked exceptions

We know that checked exceptions is an exception that must be caught, and we usually have two ways to handle it after catching the exception.

The first is to handle the exception according to the business logic, and the second is that the exception is not handled by itself, but the exception is thrown again and handled by the upper-level code.

If you capture it, but don't handle it, you ignore checked exceptions.

Next, let's consider the interrupt exception of a thread in java.

There are three very similar methods in java, interrupt,interrupted and isInterrupted.

IsInterrupted () only determines whether it is interrupted, not clears the interrupt state.

Interrupted () is a class method that calls isInterrupted (true) to determine whether the current thread is interrupted. And the interrupt state is cleared.

The first two are the methods to determine whether or not to break, and interrupt () is the method that actually triggers the interrupt.

The main points of its work are as follows:

If the current thread instance is calling the wait (), wait (long) or wait (long,int) method of the Object class or the join (), join (long), join (long,int) method, or when the Thread.sleep (long) or Thread.sleep (long,int) method is called in that instance, its interrupted state will be cleared and InterruptedException will be received.

If the thread is blocked during an I / O operation on the InterruptibleChannel, the channel will be closed, the interrupt state of the thread will be set to true, and the thread will receive a java.nio.channels.ClosedByInterruptException exception.

If the thread is in a blocked state in java.nio.channels.Selector, the interrupted state of the thread is set to true, and it immediately returns from the select operation.

If none of the above is true, set the interrupt state to true.

Look at the following example:

Public void wrongInterrupted () {try {Thread.sleep (1000);} catch (InterruptedException e) {e.printStackTrace ();}

We captured an InterruptedException in the above code, but we just printed out the exception information and didn't do anything. The performance of this program is the same as that of not sending an exception, which is obviously problematic.

As described above, we know that the interrupted () method clears the interrupt state, so if we can't handle the exception ourselves, we need to call Thread.currentThread (). Interrupt () to re-throw the interrupt, which is handled by the upper-level code, as shown below.

Public void correctInterrupted () {try {Thread.sleep (1000);} catch (InterruptedException e) {Thread.currentThread () .interrupt ();}} do not expose sensitive information in an exception

When we encounter an exception, we usually need to do a certain degree of log output to locate the exception. But when we do log output, we must be careful not to expose sensitive information.

The following table shows the sensitive information that may be exposed by abnormal information:

In addition to sensitive information, we also need to do a good job in the security of log information.

When handling caught exceptions, you need to restore the initial state of the object

If we change the state of some fields in the object while handling the exception, what do we need to do when catching the exception?

Private int age=30; public void wrongRestore () {try {age=20; throw new IllegalStateException ("custom exception!");} catch (IllegalStateException e) {System.out.println ("we do nothing");}}

In the above example, we reset age to 20 and threw an exception. Although an exception was thrown, we did not reset the age, which eventually caused the age to be modified.

The logic of the whole restore has not been processed, but we have partially modified the data of the object, which is very dangerous.

In fact, we need a reset:

Public void rightRestore () {try {age=20; throw new IllegalStateException ("custom exception!");} catch (IllegalStateException e) {System.out.println ("we do nothing"); age=30;}} do not complete finally block manually

When we use try-finally and try-catch-finally statements, we must not use return, break, continue or throw statements in finally block.

Why?

According to Java Language Specification (JLS), finally block must be executed, regardless of whether or not an exception is thrown in the try statement.

In try-finally and try-catch-finally statements, if exception R is thrown in the try statement, and then finally block is executed, there are two situations:

If the finally block executes properly, the try statement is terminated because of exception R.

If exception S is thrown in finally block, the reason why the try statement is terminated will become S.

Let's give an example:

Public class FinallyUsage {public boolean wrongFinally () {try {throw new IllegalStateException ("my exception!");} finally {System.out.println ("Code comes to here!"); return true;}} public boolean rightFinally () {try {throw new IllegalStateException ("my exception!") } finally {System.out.println ("Code comes to here!");}} public static void main (String [] args) {FinallyUsage finallyUsage=new FinallyUsage (); finallyUsage.wrongFinally (); finallyUsage.rightFinally ();}}

In the above example, we define two methods, one in which we return directly in finally, and the other in which we let finally finish executing normally.

Finally, we can see that wrongFinally hides the exception, while rightFinally retains the exception of try.

Similarly, if we throw an exception in the finally block, we must remember to catch it, otherwise the exception information in the try block will be hidden.

Do not catch NullPointerException and its parent class exception

Generally speaking, NullPointerException indicates that there is a logic error in the program code, which requires programmers to modify the logic of the code in order to fix it.

For example, add a null check.

There are three reasons why NullPointerException is not captured.

The cost of using null check is much less than the cost of exception catching.

If there are multiple statements in try block that may throw NullPointerException, it is difficult to locate the specific error statement.

Finally, if NullPointerException occurs, it is almost impossible for the program to run or recover properly, so we need to judge the null check in advance.

Similarly, the program does not capture RuntimeException, Exception, and or Throwable, the parent classes of NullPointerException.

No throw RuntimeException, Exception, or Throwable.

We throw exceptions mainly in order to find an accurate way to handle exceptions, if we directly throw RuntimeException, Exception, or Throwable, the program will not be able to accurately handle specific exceptions.

Generally speaking, we need to customize the subclasses of RuntimeException, Exception, or Throwable, and distinguish the specific exception types by specific subclasses.

Do not throw an undeclared checked Exception

Generally speaking, checked Exception needs to show catch residence, or use throws to declare on the calling method.

However, we can bypass this limitation by some means, so that we do not need to follow the above rules when using checked Exception.

Of course, this needs to be avoided. Let's look at an example:

Private static Throwable throwable; private ThrowException () throws Throwable {throw throwable;} public static synchronized void undeclaredThrow (Throwable throwable) {ThrowException.throwable = throwable; try {ThrowException.class.newInstance ();} catch (InstantiationException e) {} catch (IllegalAccessException e) {} finally {ThrowException.throwable = null;}}

In the above example, we define a private constructor for ThrowException, which will throw a throwable that is passed in from the method.

In the undeclaredThrow method, we call ThrowException.class.newInstance () to instantiate an ThrowException instance, and because the constructor needs to be called, the incoming throwable is thrown.

Because Exception is a subclass of throwable, if we pass in a checked Exception when calling, it is obvious that our code does not capture it:

Public static void main (String [] args) {ThrowException.undeclaredThrow (new Exception ("Any checked exception"));}

How to solve this problem? To put it another way, we can use Constructor.newInstance () instead of class.newInstance ().

Try {Constructor constructor = ThrowException.class.getConstructor (new Class [0]); constructor.newInstance ();} catch (InstantiationException e) {} catch (InvocationTargetException e) {System.out.println ("catch exception!");} catch (NoSuchMethodException e) {} catch (IllegalAccessException e) {} finally {ThrowException.throwable = null }

In the above example, we use the newInstance method of Constructor to create an instance of the object. Unlike class.newInstance, this method throws InvocationTargetException exceptions and encapsulates all exceptions.

So, this time we got a checked Exception.

At this point, the study on "what is the method of handling java exceptions" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

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

Servers

Wechat

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

12
Report