In depth understanding of the pros and cons of exception handling in Java programming

  • 2020-04-01 02:03:45
  • OfStack

Exception handling in Java programming is a very common topic, and almost any introductory Java course will mention it. However, I think a lot of people don't really have the right methods and strategies for dealing with exceptional situations. I would like to discuss three different levels and qualities of Java exception handling. The ways to handle exceptions described are as follows:
Good, bad and bad.
It also provides some tips on how to solve these problems.
Start by explaining some of the definitions and mechanisms that must be clarified in Java exception handling. The Java language specification calls any violation derived from the Error class or RuntimeException class an "Unchecked" exception; All other exceptions are called Checked exceptions.
By checkable exceptions, we mean exceptions that we should handle ourselves. As for methods of handling, they may be either controlled or thrown. Typically, exceptions that are known to be handled should be caught and those that are not should be notified.
For those that can't be checked, they are either out of our control (Error) or something we shouldn't have allowed in the first place (RuntimeException).
As for exception specification, the rules of Java are very simple: a method must notify itself of all verifiable exceptions that it may generate. When writing your own method, you do not have to announce every exception object that the method may actually produce. To understand when a method's throws bundle sentence must be used to announce an exception, you must know that for an exception, It can only be produced under the following four conditions :
1. Called a method that might generate an exception. For example, the readLine method of the BufferedReader class. This method notifies the java.io.ioexception exception
2. An error is found and an exception is generated with the throw statement.
3. A programming error occurred. For example, a[-1] = 0.
4.Java generated an internal error.
If one of the first two situations occurs, the person who intends to use his method must be told that if the method is used, there may be an exception (i.e. throwing on the method's head), a simple method of remembering:
Throw is called whenever a throw is involved. If a method must handle more than one exception at a time, it must indicate all exceptions in the header.
As the following example shows, they are separated by 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.
Good exception handling
Good exception handling provides a unified mechanism for handling program errors. In fact, the Java language significantly improves the ability to handle exceptions in software development by alerting callers to exceptions. This approach extends and enhances the "method" in the Java language to include its own error conditions. Let's take a look at an example that illustrates this situation.
Here 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 invoked, using the keyword "throws." This exception prompt in the method prototype increases the reliability of the programming.
Obviously, this approach alerts the caller of the method to possible exception conditions so that the caller can handle them appropriately. The following code shows how we caught and handled 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 some other nice features, such as the ability to check for exceptions, user-defined exceptions, and the new Java Logging API introduced in JDK 1.4. All subclasses of java.lang.exception belong to the checkable Exception. A checked exception is an exception that must be prompted by the method that threw the exception, which must be caught or prompted to the caller. User-defined exceptions are custom Exception classes that extend the java.lang.exception class. Good Java programs prescribe custom exception encapsulation, reporting, and handling of their own unique situations. The latest Java logging API (logging API) can centrally record exceptions. Bad Java exception handling
The bad side includes two cases: abuse of unchecked exceptions and abuse of the catchall constructor. Both ways complicate matters.
There is a class of exceptions that is a subclass of RuntimeException that is not checked by the compiler. For example, NullPointerException and ArrayStoreException are instances of this type of exception. Programmers can subclass runtimeexceptions to circumvent the limitations of checking exceptions, making it easy for the methods that generate these exceptions to be used by their callers.
Professional development teams should be allowed to do this only on rare occasions.
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 at it.
The following is an example of catchall handler:

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

I have to admit, I've used this technique myself in writing general programs; However, this type of constructor must be avoided when writing critical programs, unless they are authorized to be used in conjunction with the central fault handler.
Beyond that, the catchall constructor is simply a mechanism for speeding up programming by avoiding error handling.
One disadvantage of exception handling is that it is difficult to adopt a good error handling strategy. Exceptions such as recovery from low capacity memory state, write errors, and algorithm errors are not easily resolved. You can try some common techniques such as recycling, garbage collection, and alerting users to cope.
Bad handling
Like many Java features and their apis, Java's exception-handling mechanism has its share of goofy "overlord" bugs. For example, to throw an exception and not hesitate to allocate memory for it with the "new" keyword is an example.
I don't know how many times I've made this mistake and run into a wall with a serious compiler. In this case, we're all trying to help the language rather than make it work for us. And the OutOfMemoryErrors that we encountered were defects in exception handling. This process is:
Use the finally module to close the file and resolve the exception to get the method and line of code that went wrong. The biggest drawback in this process is the need to catch an OutOfMemoryError, which is not a verifiable exception! When you think about it, running out of memory is pretty common. Any program that is closely related to the state of memory usage should catch and handle this error.
Some Suggestions for using exceptions
Exception control is not designed to replace simple tests. Use exceptions only in exceptional cases!
2. Don't over-specify exceptions. Instead of attaching exception handling to every statement, it's best to put the entire task in the try block. If one of the operations fails, the task can be aborted.
3. Don't "suppress" anomalies. For methods that need to announce exceptions, we can use the catch method instead to force the exception off, and if an exception does occur, that exception will be "silently" ignored. If you feel that an exception is going to be important, you have to work harder to control it properly.
4. Don't mind passing exceptions. If the method being called produces an exception, such as the readLine method, they naturally catch the exception that they might, in which case it is better to pass the exception instead of catching it yourself.

Related articles: