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

How to handle exceptions in Java

2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

This article will explain in detail how to handle exceptions in Java. The content of the article is of high quality, so the editor will share it with you for reference. I hope you will have some understanding of the relevant knowledge after reading this article.

Exception and exception handling

What is an anomaly? It can be summed up in one sentence: the abnormal situation that occurs during the execution of the program. Exceptions occur when something goes wrong, such as opening a file that doesn't exist, trying to call a method on an object that is null, and so on.

An exception is unpredictable, but once it occurs, it needs exception handling, which can be said to improve greatly if you know something wrong. Exception handling is an error handling mechanism, and if you don't do anything about the exception, the exception will cause the application to crash.

Once you choose to handle the exception, it means that you acknowledge the problem and take the necessary steps to make the application recover from the error, so as to keep the business going and prevent the application from crashing.

In fact, exception handling is not the only way to deal with problems. Today's high-level languages generally have exception handling mechanisms, but older languages such as C handle exceptions by returning error codes. For example, the common return value of an array out of bounds is-1.

The advantage of this approach is that the code logic is easy to reason and there are no interruptions and code jumps. On the other hand, this approach encourages the caller of the function to always check the error code returned. However, this kind of check is easy to cause code pollution and reduce the readability and maintainability of the code.

Another serious disadvantage of the error code is the lack of context information. You may know that the error code "- 5" means that the file cannot be found, but which file can not be found! The error code cannot be expressed.

Error codes are generally used in process-oriented languages, and some scenarios are powerless for object-oriented high-level languages, such as constructor exceptions that cannot return error codes.

Exception handling

When an exception is thrown, the flow of the application is interrupted, and if the exception is not handled in time, the application crashes. Users will see abnormal information, but most of that information they do not understand, which will be a very bad user experience, in fact, abnormal information can also be packaged as very friendly prompts.

So exception handling must be done, even in order to improve the user experience, log problems, exit the application gracefully, and so on.

We can use code blocks (try...catch...) When an exception occurs, the code is executed through try. If an exception occurs, the flow of the application is transferred to catch, and the catch catches the exception and handles it as necessary.

The principle of exception handling described above is still quite abstract for beginners. Let's give an example.

Package com.zqf

Public class App

{

Public static void main (String [] args) {

System.out.println ("First line")

System.out.println ("Second line")

System.out.println ("Third line")

/ / initialize a group of elements with three elements

Int [] myIntArray = new int [] {1,2,3}

Print4thItemInArray (myIntArray)

System.out.println ("Fourth line")

System.out.println ("Fith line")

}

Private static void print4thItemInArray (int [] arr) {

/ / gets the fourth (subscript 3) element and throws an exception because there is none

System.out.println (arr [3])

System.out.println ("Fourth element successfully displayed!")

}

}

Analyze the program, initialize an array of three elements in main, pass the array to the private method print4thItemInArray, and try to get the fourth element of the array in print4thItemInArray. Since no fourth element will throw a "ArrayIndexOutOfBoundsException" exception, the application will only print to "Third line".

The output result of executing the application is as follows

First line

Second line

Third line

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3

At com.zqf.App.print4thItemInArray (App.java:20)

At com.zqf.App.main (App.java:14)

Process finished with exit code 1

Now let's modify it and add exception handling.

Package com.zqf

Public class App {

Public static void main (String [] args) {

System.out.println ("First line")

System.out.println ("Second line")

System.out.println ("Third line")

/ / initialize a group of elements with three elements

Int [] myIntArray = new int [] {1,2,3}

Try {/ / catch exception

Print4thItemInArray (myIntArray)

} catch (ArrayIndexOutOfBoundsException ex) {/ / exception handling

System.out.println ("Have no four items!")

}

System.out.println ("Fourth line")

System.out.println ("Fith line")

}

Private static void print4thItemInArray (int [] arr) {

/ / gets the fourth (subscript 3) element and throws an exception because there is none

System.out.println (arr [3])

System.out.println ("Fourth element successfully displayed!")

}

}

Now run it and see the output.

First line

Second line

Third line

Have no four items!

Fourth line

Fith line

In fact, the exception will still occur this time, because the fourth element does not exist, so in "Fourth element successfully displayed!" An exception is thrown before the output, interrupting the execution process, but the process jumps to the catch statement block, and catch prints only a "Have no four items" to continue execution.

Java anomaly system

In Java, all exceptions have a common ancestor, Throwable, which has two subclasses: Exception (exception) and Error (error), each of which has a large number of subclasses. The commonness and difference between Exception (exception) and Error (error): both can be caught, but the former can be handled by the application itself, while the latter is serious and cannot be recovered.

Best practic

1 Clean up resources with Finally or Try-With-Resource

We often use resources, such as InputStream, in the try statement block, which needs to be turned off after use. A common mistake is to close the resource in the try statement block. Such as

Public void doNotCloseResourceInTry () {

FileInputStream inputStream = null

Try {

File file = new File (". / tmp.txt")

InputStream = new FileInputStream (file)

/ / use inputStream to read files

/ / Don't do this

InputStream.close ()

} catch (FileNotFoundException e) {

Log.error (e)

} catch (IOException e) {

Log.error (e)

}

}

This approach seems perfect, no exceptions are thrown, all statements are executed in try, and IputStream is closed to release resources. But think about this: what if an exception was thrown before the "inputStream.close ()" statement? The normal process is interrupted and redirected, resulting in InputStream not being shut down at all.

Therefore, you should put the code that cleans up resources in finally or try-with-resource statements. Whether the try statement block is executed normally or the exception is handled, the finally statement block will be executed, and you need to make sure that all open resources are closed in finally.

Public void doNotCloseResourceInTry () {

FileInputStream inputStream = null

Try {

File file = new File (". / tmp.txt")

InputStream = new FileInputStream (file)

/ / use inputStream to read files

} catch (FileNotFoundException e) {

Log.error (e)

} catch (IOException e) {

Log.error (e)

} finally {

If (inputStream! = null) {

Try {

InputStream.close ()

} catch (Exception e) {

Log.error (e)

}

}

}

}

The syntax of try-with-resource is introduced in JDK7. To put it simply, when a resource object (such as an InputSteam object) implements the AutoCloseable interface, you can create an instance in parentheses after the try keyword. When the try-catch statement block is executed, the resource is automatically closed, and the code is much simpler. As follows

Public void doNotCloseResourceInTry () {

File file = new File (". / tmp.txt")

Try (FileInputStream inputStream = new FileInputStream (file)) {

/ / use inputStream to read files

} catch (FileNotFoundException e) {

Log.error (e)

} catch (IOException e) {

Log.error (e)

}

}

two

Throw a specific exception

The more specific the exception you throw, the better. Colleagues who are not familiar with your code or you a few months later may need to call these methods and handle the exception, so provide as much information as possible to make your API easier to understand. For example, do not use IllegalArgumentException if you can use NumberFormatException, and absolutely avoid using non-specific Exception classes directly.

/ / not recommended

Public void doNotDoThis () throws Exception {...}

/ / suggestion

Public void doThis () throws NumberFormatException {...}

3. Make comments / documentation.

As long as you declare an exception in the method, you need to comment on the Javadoc. This has the same goal as the previous best practice: provide the caller with as much information as possible so that exceptions can be avoided or handled. So make sure that you add the "@ throws" declaration to Javadoc and describe the situation that caused the exception.

/ * *

* This method does something extremely useful...

*

* @ param input

* @ throws MyBusinessException if... Happens

, /

Public void doSomething (String input) throws MyBusinessException {...}

4 exceptions carry descriptive information

This best practice is somewhat similar to the first two, but this one provides information not only for method callers, but also for logging or monitoring tools to facilitate troubleshooting. In fact, the general exception class name already describes the type of problem, you do not have to provide a lot of additional information, just be concise and concise. NumberFormatException, for example, provides a short and clear text description when the java.lang.Long constructor throws an exception.

Try {

New Long ("xyz")

} catch (NumberFormatException e) {

Log.error (e)

}

The name of NumberFormatException already tells you the type of exception, and the information it carries only tells you that the string provided will cause the exception, but if the name of the exception cannot express the type of exception, you need to provide more information. The above exception information is as follows

ERROR TestExceptionHandling:52-java.lang.NumberFormatException: For input string: "xyz"

If you take a closer look at the source code of JDK, you will see that java.lang.Long does various checks in the constructor. When some verification fails, NumberFormatException.forInputString will be called, and the static method forInputString will format the construction parameters of java.lang.Long and then construct a new NumberFormatException instance and throw

/ * *

* Factory method for making a NumberFormatException

* given the specified input which caused the error.

*

* @ param s the input causing the error

, /

Static NumberFormatException forInputString (String s) {

Return new NumberFormatException ("For input string:\"+ s +"\ "")

}

5 lines to catch subclass anomalies

Many IDE will help you with best practices. If you catch the parent class exception first and then the subclass exception, they will tell you that the later code is unreachable or the warning has been caught because it is executed in the order of the catch in the code.

So if you catch IllegalArgumentException first, you won't be able to catch its subclass NumberFormatException, so the best time is always to catch more informative exceptions (subclasses) before catching the parent class. Such as

Public void catchMostSpecificExceptionFirst () {

Try {

DoSomething ("A message")

} catch (NumberFormatException e) {

Log.error (e)

} catch (IllegalArgumentException e) {

Log.error (e)

}

}

6 do not capture Throwable

From the diagram of the Java exception system, we can see that Throwable is the ancestor of all Exception and Error. Throwable can be caught, but please do not catch it. If you catch Throwable, you not only catch exceptions, but also catch errors. But the error is unrecoverable, it is a serious error thrown by JVM, and there is nothing the application can do about it.

/ / do not capture Throwable

Public void doNotCatchThrowable () {

Try {

/ / do something

} catch (Throwable t) {

/ / don't do this!

}

}

7 do not ignore exceptions

Do you remember when when you were analyzing bug, you encountered code that only executed the first half of the code, but you don't know why? Some developers often catch exceptions, but it is empirically believed that the exception decision is impossible, resulting in no exception handling.

Public void doNotIgnoreExceptions () {

Try {

/ / do something

} catch (NumberFormatException e) {

/ / this will never happen,I'm sure!!

}

}

In fact, it happens in most cases, because over time and business logic changes, the content of the try code block changes, resulting in exceptions, and your confidence harms not only you but also future generations. It is recommended to keep at least one log in catch to inform you of abnormal problems and facilitate troubleshooting.

Public void logAnException () {

Try {

/ / do something

} catch (NumberFormatException e) {

Log.error ("This should never happen:"

+ e + ", but I get a mistake!")

}

}

8 do not throw an exception up after only logging

"Don't throw an exception up after just logging" is one of the most overlooked best practices. You will find that exceptions are often caught, logged, and then thrown in a large number of code snippets and even class libraries.

Try {

New Long ("xyz")

} catch (NumberFormatException e) {

Log.error (e)

Throw e

}

The intuitive feeling is to record an exception, and then throw an exception so that the caller can handle it properly, but multiple logging of the same exception can be confusing, please refer to the fourth best practice: concise and concise.

ERROR TestExceptionHandling:65-java.lang.NumberFormatException: For input string: "xyz"

Exception in thread "main" java.lang.NumberFormatException: For input string: "xyz"

At java.lang.NumberFormatException.forInputString (NumberFormatException.java:65)

At java.lang.Long.parseLong (Long.java:589)

At java.lang.Long. (Long.java:965)

At com.stackify.example.TestExceptionHandling.logAndThrowException (TestExceptionHandling.java:63)

At com.stackify.example.TestExceptionHandling.main (TestExceptionHandling.java:58)

If you really need to provide more information to the caller, you can refer to the next best practice: packaging exceptions.

9 abnormal packaging without consumption

It is advisable to catch the standard exception, customize the wrapper exception according to the actual business, and then throw it up. When packing the exception, the original exception is usually passed in as a construction parameter, otherwise the tracking information of the stack will be lost and the analysis will be difficult.

Public void wrapException (String input) throws MyBusinessException {

Try {

/ / do something

} catch (NumberFormatException e) {

Throw new MyBusinessException ("A message that describes the error." e)

}

}

So much for sharing about how to handle exceptions in Java. I hope the above content can be helpful to you and learn more knowledge. If you think the article is good, you can share it for more people to see.

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

Internet Technology

Wechat

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

12
Report