Thinking in Java - Study Notes - (12) Handling Errors Through Exceptions

Java Programming Ideas - Chapter 12 - Handling Errors Through Exceptions

The basic philosophy of Java is that poorly structured code cannot run.

The ideal time to find bugs is during the compilation phase. Some errors must be resolved during runtime.
Improved error recovery mechanisms are the most powerful way to provide code robustness.

Using exceptions often reduces the complexity of error-handling code. Separate the code that "describes what to do during normal execution" from the code that says "what to do when something goes wrong."

Basic exception

An exceptional condition is a problem that prevents the current method or scope from continuing to execute. For abnormal situations, because the necessary information cannot be obtained to solve the problem in the current environment, it can only jump out of the current environment and submit the problem to the upper-level environment.

When an exception is thrown, several things follow.

1) First, like the creation of other objects in Java, the exception object will be created on the heap using new .

2) Then, the current execution path (which cannot go on) is terminated and the reference to the exception object is popped from the current environment.

3) The exception handling mechanism takes over the program and starts looking for an appropriate place to continue the program execution.

The proper place is an exception handler , whose job is to recover the program from an error state so that the program can either run in a different way or continue to run.

Exceptions allow us to think of everything as a transaction, and exceptions guard the bottom line of those transactions. We can also think of exceptions as a built-in recovery (undo) system, because (with careful use) we can have various recovery points in the program.

One of the most important aspects of exceptions is that if something goes wrong, they won't allow the program to continue along its normal path.

Terminate and resume

There are two basic models of exception handling in theory: termination model and recovery model

The recovery model is not very practical, and the main reason for this is probably the coupling it causes: the recovery handler needs to know where the exception was thrown, which inevitably involves non-generic code that depends on the location of the recruitment.

exception statement

    void f() throws TooBig, TooSmall, DivZero { //...

catch all exceptions

stack trace

public class WhoCalled {
    static void f() {
        // Generate an exception to fill in the stack trace
        try {
            throw new Exception();
        } catch (Exception e) {
            for (StackTraceElement item : e.getStackTrace()) {
                System.out.println(item.getMethodName());
            }
        }
    }
    static void g() { f(); }
    static void h() { g(); }

    public static void main(String[] args) {
        f();
        System.out.println("---------------------");
        g();
        System.out.println("---------------------");
        h();
    }
}
输出结果
f
main
---------------------
f
g
main
---------------------
f
g
h
main

Java standard exception

RuntimeException

    if (ref == null)
        throw new NullPointerExcception;

If the call is made on null , Java will automatically throw a NullPointerException , so the above writing is unnecessary.

Only exceptions of type RuntimeException (and its subclasses) can be ignored in the code, the handling of other types of exceptions is enforced by the compiler. The reason, RuntimeException represents a programming error:

1) Unforeseen errors such as null references

2) As a programmer, errors that should be checked in the code

Use finally for cleanup

Finally is very important for languages ​​without garbage collection and automatic destructor invocation mechanisms . It enables the programmer to guarantee that no matter what happens in the try block, the memory will always be freed. But Java has garbage collection mechanism, so memory freeing is no longer a problem. Also, Java doesn't have a destructor to call. So under what circumstances can Java use finally ?

The finally clause is used when resources other than memory are to be restored to their original state . The resources that need to be cleaned up include: open files or network connections, graphics drawn on the screen, etc. The finally clause is also executed when break and continue statements are
involved . Execution is also guaranteed in return .

Disadvantage: Abnormal loss

    public static void main(String[] args) {
        try {
            throw new RuntimeException();
        }
        finally {
            // 不产生任何输出
            return;
        }
    }
注释掉 return 一行后
Exception in thread "main" java.lang.RuntimeException
    at thinkinginjava.WhoCalled.main(WhoCalled.java:19)

Unusual restrictions

When overriding a method, only those exceptions listed in the base class method's exception specification can be thrown.

Constructor

For classes that may throw exceptions during construction and require cleanup, the safest way to use them is to use nested try clauses:

public class Cleanup {
    public static void main(String[] args) {
        try {
            InputFile in = new InputFile("Cleanup.java");
            try {
                String s;
                int i = 1;
                while((s = in.getLine()) != null)
                    // perform line-by-line processing here
            } catch(Exception e) {

            } fanilly {
                in.dispose();
            }
        } catch(Exception e) {
            System.out.println("InputFile construction failed");
        }
    }
}

An important principle of exception handling is "catch exceptions only if you know how to handle them". In fact, an important goal of exception handling is to separate error-handling code from where the error occurred.

"Checked Exception":

If you don't know how to handle exceptions, you can use exception chains to wrap "checked exceptions" in RuntimeException .

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324714515&siteId=291194637