Exception Handling in Java programming is a very common topic. Almost any introductory Java course will mention exception handling. However, I think that many people do not really have the correct methods and strategies for handling exceptions, so they do not have to understand the concept at most. This article discusses three Java Exception Handling Methods with different degrees and quality. The methods described in this article are divided into the following:
Good, bad, and bad.
At the same time, we provide you with some tips to solve these problems.
First, explain some definitions and mechanisms that must be clarified in java exception handling. Any violation derived from the Error or RuntimeException class is called an Unchecked exception. All other exceptions are called Checked exceptions.
The so-called checkable exception refers to the exception we should handle on our own. As for the processing methods, either try catch or throws may generate them. Typically, exceptions that are known to be handled should be captured, and exceptions that do not know how to be handled should be advertised.
For non-checkable exceptions, they are either out of our control or we should not allow them first (RuntimeException ).
As for exception designation, Java rules are very simple: A method must notify itself of all possible checkable exceptions. When writing your own method, you do not have to advertise every exception object that may actually occur in the method. To understand when an exception must be advertised through the throws clause, for an exception, it must be known that it will only generate in the following four situations:
1. Call methods that may cause exceptions. For example, the BufferedReader class readLine method. Java. io. IOException is advertised in this method.
2. An error is detected and throw statements are used to generate an exception.
3. a programming error occurs. For example, a [-1] = 0.
4. Java generates an internal error.
In either of the first two cases, you must inform the person who intends to use the method: If you use this method, an exception may occur (that is, using throws on the method header ), A simple memory method:
Throws must be advertised as long as throw is included. If a method must handle multiple exceptions at the same time, all exceptions must be indicated in the header. As shown in the following example, use commas to separate them:
1234567
Class Animation
{
Public Image loadImage (Strint s) throws EOFException, MalformedURLException
{
......
}
}
However, we do not need to advertise internal java errors or exceptions derived from RuntimeException.
Handle exceptions
Exception Handling provides a unified mechanism for handling program errors. In fact, the Java language significantly improves the exception handling capability in software development by issuing an exception warning to the caller. In this way, the "method" in the Java language is extended and enhanced to include its own error conditions. Let's look at an example. This example illustrates this situation.
The following is a prototype of the FileInputStream constructor:
Public FileInputStream (String name) throws FileNotFoundException Java
The method and constructor must declare the exception that they may "throw" when being called. The keyword used is "throws ". This exception prompt in the method prototype increases programming reliability.
Obviously, this method prompts the method caller with possible exception conditions so that the caller can properly handle these exceptions. The following code illustrates how we capture and handle the FileNotFoundException exception:
1234567891011
Try
{
FileInputStream FCM = 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 also has some other excellent features, such as checking exceptions, user-defined exceptions, and the new Java Logging API (Java Logging API) introduced in JDK 1.4 ). All subclasses of java. lang. Exception belong to checkable exceptions. Checked exception is an exception that must be thrown by the method that throws the exception. This exception must be caught or thrown to the caller. User-defined exceptions are custom Exception classes that extend the java. lang. Exception class. Excellent Java programs require custom exception encapsulation, reporting, and handling of their own unique situations. The latest Java logging API (logging API) records exceptions in a centralized manner. Poor Java Exception Handling
The negative side includes two situations: Misuse of unchecked exceptions and misuse of the catchall constructor. Both methods make the problem complicated.
A type of exception is a subclass of RuntimeException, which is not checked by the compiler. For example, NullPointerException and ArrayStoreException are instances of this type of exception. Programmers can subclass RuntimeException to avoid the restriction of checking exceptions, so that the methods that generate these exceptions are 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 capture code module that can handle all possible exceptions thrown to it.
The following are examples of catchall processors:
123456789
Try
{
// Code here with checked exceptions
}
Catch (Throwable t)
{
T. printStackTrace ();
}
I have to admit that I have used this technology when writing General programs. However, this type of constructor must be avoided when writing key programs, this can be done unless they are authorized to work with the central error processor.
In addition, the catchall constructor is only a mechanism to speed up programming by avoiding error processing.
One disadvantage of exception handling is that it is difficult to adopt an excellent error handling policy. Recovery from low-volume memory status, write errors, algorithm errors, and other exceptions are not easily solved. You can try common technologies such as recycling, garbage collection, and reminding users to cope with the above situation.
Bad Solution
Similar to many Java features and their APIs, Java's Exception Handling Mechanism also has a funny error in the "Overlord hard bow" class. For example, in order to throw an exception, we did not hesitate to use the keyword "new" to allocate memory for it.
I don't know how many times I have repeatedly hit the wall in the face of serious compilers because of such errors. In this case, we are all waiting for the language instead of letting the language be used by us. In addition, the OutOfMemoryErrors we encountered is a defect in exception handling. This process is:
Use the finally module to close the file and parse the exception to obtain the problematic method and code line. The biggest defect in this process is that OutOfMemoryError needs to be captured, but this exception is not checkable! Think about it. Memory depletion is quite common. Any program closely related to memory usage should capture and handle this error.
Some suggestions for exceptions
1. The design purpose of exception Control is not to replace some simple tests. Use exceptions only when exceptions exist!
2. Do not over-Detail exceptions. Do not add exception handling to each statement. It is best to place the entire task in the try block. If one of the operations fails, you can discard the task immediately.
3. Do not "Suppress" exceptions. For methods that require an exception notification, we can use the capture method to forcibly disable the exception. If an exception occurs, the exception will be "quietly" ignored. If you think the exceptions will be very important, you must spend more time and control them correctly.
4. Do not mind passing exceptions. If the called method produces exceptions, such as the readLine method, they are born to capture their own exceptions. In this case, a better way is to pass these exceptions out, instead of capturing it by yourself.