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 advantages and disadvantages of Java exception handling

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

Share

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

This article introduces the relevant knowledge of "what are the advantages and disadvantages of Java exception handling". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

First explain some definitions and mechanisms that must be understood in java exception handling. The Java language specification refers to any violation derived from the Error or RuntimeException classes as "Unchecked" exceptions; all other exceptions are called "Checked" exceptions.

The so-called detectable exception refers to the exception that we should handle by ourselves. As for the means of handling, either control (try catch) or notify (throws) that they may arise. In general, you should catch exceptions that you know how to handle and notify those that do not know how to handle them.

For those undetectable exceptions, they are either out of our control (Error) or we should not allow them in the first place (RuntimeException).

As for the specification of exceptions, the rule of Java is very simple: a method must notify itself of all detectable exceptions that may be generated. When writing your own method, it is not necessary to announce every exception object that the method may actually produce. To understand when it is necessary to use the method's throws series to notify an exception, you must know that for an exception, it can only be generated in the following four situations:

1. A method that might generate an exception was called. For example, the readLine method of the BufferedReader class. This method notifies the java.io.IOException exception

two。 An error was detected and an exception was generated with the throw statement.

3. A programming error occurred. For example, a [- 1] = 0.

An internal error occurred in 4.Java.

If one of the first two situations occurs, you must tell the person who intends to use your own method that if you use this method, it may cause an exception (that is, using throws on the method header), a simple memory method:

Notify throws as long as it contains throw. If a method must handle multiple exceptions at the same time, all exceptions must be pointed out in the header. As shown in the following example, divide them with commas:

Class Animation {public Image loadImage (Strint s) throws EOFException,MalformedURLException {. }}

However, we do not need to notify internal java errors, nor should we notify exceptions derived from RuntimeException.

Okay, exception handling.

Good exception handling provides a unified mechanism for handling program errors. In fact, the Java language significantly improves the ability of exception handling in software development by issuing exception warnings to callers. This approach extends and enhances the "method" in the Java language to include its own error conditions. Let's look at an example that illustrates this situation.

The following is a prototype of one of the FileInputStream constructors:

Public FileInputStream (String name) throws FileNotFoundException Java

Methods and constructors must declare exceptions that they may "throw" when called, with the keyword "throws". This exception hint in the method prototype increases the reliability of programming.

Obviously, this approach prompts the caller of the method of possible exception conditions, so that the caller can handle these exceptions appropriately. The following code shows how we catch and handle the FileNotFoundException exception:

Try {FileInputStream fis = new FileInputStream (args [0]); / / other code here...} catch (FileNotFoundException fnfe) {System.out.println ("File:" + args [0] + "not found. Aborting."); System.exit (1);}

Java exception handling has other excellent features, namely, the ability to check for exceptions, user-defined exceptions, and the new Java logging API (Java Logging API) introduced in JDK 1.4. All subclasses of java.lang.Exception are detectable exceptions. A checked exception is an exception that must be prompted by the method that throws the exception, which must be caught or prompted to the caller. User-defined User-defined exceptions are custom exception classes that extend the java.lang.Exception class. Good Java programs provide for custom exception encapsulation, reporting, and handling their own unique conditions. The Java record API (logging API) of * can record exceptions centrally.

Bad Java exception handling

The downside includes two situations: abuse of undetectable exceptions (unchecked exceptions) and abuse of catchall constructors. Both ways complicate the problem.

There is a category of exceptions that belong to a subclass of RuntimeException and are not checked by the compiler. For example, NullPointerException and ArrayStoreException are examples of this type of exception. Programmers can subclass RuntimeException to avoid the limitations of checking for exceptions so that the methods that generate these exceptions can be used by their callers.

Professional development teams should only be allowed to do so in rare cases.

The second bad habit of exception handling is the catchall constructor. The so-called "catchall constructor" is an exception catching code module that handles all possible exceptions thrown to it.

The following is an example of a catchall processor:

Try {/ / code here with checked exceptions} catch (Throwable t) {t.printStackTrace ();

I have to admit that I have used this technique myself when writing general programs; however, this type of constructor must be avoided when writing critical programs, unless they are authorized to use it in conjunction with the central error processor.

Beyond that, the catchall constructor is nothing more than a mechanism to speed up programming by avoiding error handling.

One of the shortcomings of exception handling is that it is difficult to adopt good error handling strategies. Exceptions such as recovery from low-capacity memory state, write errors, and algorithm errors can not be easily resolved. You can try common techniques such as looping, garbage collection and reminding users to deal with the above situation.

A bad way to deal with

Like many Java features and their API, Java's exception handling mechanism also has the "overlord hard bow" kind of funny error. For example, you don't hesitate to allocate memory to an exception with the keyword "new" in order to throw it.

I don't know how many times I've hit a brick wall in front of a serious compiler because I made such a mistake. In this case, we are actually serving the language rather than making it available to us. And the OutOfMemoryErrors we encountered is the flaw in exception handling. This process is as follows:

Use the finally module to close the file and parse the exception to get the method and line of code that went wrong. The flaw in this process is that the OutOfMemoryError needs to be caught, but this exception is not a detectable exception! Come to think of it, memory exhaustion is quite common. Any program that is closely related to memory usage should catch and handle this error.

Some suggestions when using exceptions

1. Exception control is not designed to replace simple tests. Use exceptions only in exceptional cases!

two。 Don't refine exceptions too much. Instead of adding exception handling to every statement, * places the entire task in a try block. If one of the operations fails, you can immediately abandon the task.

3. Do not "suppress" exceptions. For the method that needs to notify the exception, we can use the capture method to forcibly close the exception, and if the exception does occur, the exception will be quietly ignored. If you feel that the exception will be very important, you must make more efforts to control it correctly.

4. Don't mind the abnormal transmission. If the called method produces an exception, such as the readLine method, they are naturally able to catch the exception they may generate, in which case it is better to pass the exception out rather than catch it yourself.

This is the end of the content of "what are the pros and cons of Java exception handling". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

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