Java Exceptions

1. Common misclassification

General, errors can be divided into the following categories:

  • user input errors
  • device errors or physical limitations
  • code errors

2. A common error handling

2.1 error code

One commonly used method of error handling is returned error code, made by calling method in accordance with different processing error code.

However, under some circumstances error code is not convenient to use, such as how to get points with the error code and error code the same rms.

2.2 exception handling

The mission of exception handling is to transfer control from where the error occured to an error handler that can deal with the situation.

When an error occurs, the program should be restored to a safe state and start over, or to save the current job security exit, but this is not easy, the key is how to program control jumps from place to place triggered the error handling errors.

Java allows every method an alternative exit path if it is unable to complete its task in the normal way:

  • 首先,throws an object that encapsulates the error information
  • 然后,the exception-handling mechanism begins its search for an exception handler that can deal with this particular error condition
  • Note that this alternative exit path logic has nothing to do with the normal procedure, the method exits immediately, and it does not return its normal value, and the execution does not resume at the code that called the method

3. Java exception hierarchy

3.1 Throwable

It is the base class Throwable whole Java exception hierarchy, which is subdivided into:

  • Error
  • Exception

3.2 Error

the error hierarchy describes internal errors and resource exhaustion situations inside the Java runtime system.

You should not throw an object of this type. There is little you can do if sucn an internal error occurs, beyond notifying the user and trying to terminate the program gracefully.

3.3 Exception

Exception can be divided into two categories:

  • RuntimeException
  • other

RuntimeException mean coding errors, such as
a bad cast, an out-of -bounds array access, a null pointer access and so on.

Other Exception is usually something unexpected, some bad things happened, for example, to open a file that does not exist.

Why not open a file that does not exist RuntimeException? Because this is not your code can control, you first check whether a file exists is useless, when you might check is there, but when you open does not exist.

4. Checked exception vs unchecked exception

Error and RuntimeException these two, we called unchecked exception.

In addition to other Exception Error and RuntimeException these two away, we called checked exception.

The compiler checks that you provide exception handlers for all checked exceptions:

  • For Error, you do nothing, it is unchecked exception
  • For RuntimeException, coding error is your responsibility, you should avoid them appear, it is also unchecked exception
  • For other exceptions, you must be prepared to deal with them, it is checked exception

5. Checked exception declaration

For checked exceptions might be thrown your way, you must declare throws out by the method declaration.

If possible, throw more checked exceptions, you need are listed, separated by commas.

public Image loadImage(String name) throws FileNotFoundException, EOFException {...}

Note that, unchecked exception should not appear in your throws statement:

  • For Error, you can do nothing
  • For RuntimeException, you should avoid as they appear, rather than a statement might throw them.

6. Throw an exception

How to throw an exception it? It is simple:

  • find an appropriate exception class
  • make an object of that class
  • throw it

No suitable standard exception class available? Does not matter, you can customize a

class FileFormatException extends IOException {
    public FileFormatException() {}
    public FileFormatException(String gripe) {
        super(gripe);
    }
}

Generally, we provide two constructors for the custom exception class: a default constructor and a constructor with a detailed message.

7. Catch exceptions

try {
    xxx
} catch (ExceptionType1 | ExceptionType 2 e) {
    xxx
} catch (ExceptionType3 e) {
    xxx
}

For checked exceptions, if you know how to handle them, then you can catch them, so do not throw them.

As a general rule, you should catch those exceptions that you know how to handle and propagate those that you do not know how to handle.

8. Rethrow exceptions

try {
    xxx
} catch (SQLException e) {
    throw new ServletException("xxx error").initCause(e);
}

This is a common way of rethrow exception. In this way, we can wrap a more abstract Exception, or converting a checked exception into a RuntimeException.

9. finally

try {
    try {
        xxx
    } finally {
        xxx
    }
} catch (Exception e) {
    xxx
}

the inner try block has a single responsibility: to make sure that the resources are released

the outer try block has a single responsibility: to ensure that errors are reported.

注意,the body of the finally clause is intended for cleaning up resources. Don't put statements that change the control flow (return, throw, break, continue) inside a finally clause.

10. try-with-Resources

try (Resource res = xxx) {
    xxx
}

From Java 7, try-finally structure can be simplified as try-with-Resources.

Resource requirements must be AutoCloseable implementation class, when the try block exits, then res.close () is called automatically.

A difficulty arises when the try block throws an exception and the close method also throws an exception. The original exception is rethrown, and any exceptions thrown by close methods are considered "suppressed". They are automatically caught and added to the original exception with the addSuppressed method.

Guess you like

Origin www.cnblogs.com/liuxuhelloworld/p/12005168.html