"Java Core Technology" Reading Notes (3)-Exception Handling

JavaCoreNote-exception

If some operations are not completed due to an error, the program should:
• return to a safe state and allow the user to execute some other commands; or
• allow the user to save the results of all operations and terminate the program in a proper manner

abnormal

for: transfer control from the place where the error occurred to an error processor capable of handling this situation

Program error classification:

  1. User input
  2. Physical restrictions
  3. device
  4. Code
    processing method: return a special error code; do not return any value, but throw an object that encapsulates the exception information, and find the corresponding error handler.

grammar

classification
  • Unchecked exceptions (unchecked)
    Error, RuntimeException
    Error class hierarchy describes internal errors and resource exhaustion errors of the Java runtime system;
    RuntimeException: exceptions caused by program errors, including the situation:

    • Wrong type conversion
    • Array access out of bounds
    • Accessing the null pointer
      If a RuntimeException occurs, it must be the programmer's problem
  • Checked exception (checked)
    non-RuntimeException means that the program itself is no problem, but due to exceptions such as IO errors

When to declare
  1. Call a method that throws the checked exception
  2. An error was found during the running of the program, and a checked exception was thrown using the throw statement
  3. The program has an error and throws an unchecked exception
  4. Internal errors in virtual machines and runtime libraries

Note: Errors inherited from Error and exceptions inherited from RuntimeException should not be declared

A method must declare all checked exceptions that may be thrown, and non-checked exceptions are either uncontrollable (Error) or should be avoided (RuntimeException)

Throw an exception
  1. Find the appropriate exception class
  2. Create exception class object
  3. Throw object

Define the exception class: a class derived from Exception or its subclasses, providing two constructors
Note: The throws specifier of the subclass is not allowed to exceed the scope of the exception class listed by the superclass method

Catch exception
  • try / catch block
  • When to catch and when to throw? -What exceptions you know how to handle
  • When catching multiple exceptions, the anomaly variable is implicitly a final variable
  • The exception can be thrown again in the catch statement. In order to convert the type of exception, the cause of the exception can be set initCause, getCause can be re-acquired
finally clause

for: resource recycling problem, if there is no finally clause, the same code will appear in two places.
The return clause in the finally clause will override the return in the try

Decoupling try / catch and try / finally statement blocks, the inner layer is responsible for closing resources, and the outer layer is responsible for ensuring that exceptions are reported

InputStrean in = . . .;
try
{
    try
    {
        code that might throwexceptions
    }
    finally
    {
        in.cose(); 
    } 
}
catch (IOException e) {
    show error message
}

The finally clause may generate an exception, overwriting the original exception information.

Try statement with resources
  • The resource belongs to the class that implements the AutoClosable interface and will automatically call the close method.
  • Try statements with resources can also have their own catch, finally clauses, these clauses will be executed after the call to close the resource. In practice, avoid adding too much content, and this is rarely used in this way.
    For the problem that the finally clause generates an exception that covers the original exception, the addSuppressd method is automatically called to add it to the suppressed exception of the original exception, and the original exception is thrown. The processor can call getSuppressed to obtain the exception list.
Stack trace
  • Throwable.printStackTrace、getStackTrace
  • Thread.getAllStackTrace

skills

  1. Exception handling cannot replace simple tests
  2. Don't over-refine the exceptions and make the code bloat
  3. Leverage exception hierarchy
  4. Don't suppress abnormal
  5. When detecting errors, harshness is better than laissez-faire (throw early)
  6. Don't be shy about passing exceptions (late catch)

Affirmation

for: selectively enable detection

The assertion mechanism allows some check statements to be inserted into the code during testing. When the code is released, these inserted detection statements will be automatically removed

use

  1. assert condition;
    assert condition: expression;
    AssertionError exception is thrown when the condition is not established, the expression in the second form generates a description string.

  2. Enabling and disabling
    does not require recompilation, is the function of the class loader.
    Enable: -enableassertions or -ea
    can be enabled in a class or package:
    java -ea: MyClass -ea: com.mycompany.mylib ... MyApp is
    disabled: -disableassertions or -da

For system classes (no class loader), use: enablesystemassertions / -esa
program can also be controlled, see API

  1. When to use
  • Assertion failure is a fatal, unrecoverable error;
  • Assertion checking is only used in the development and testing phase

Log

Logging API advantages:

  1. It is easy to open, cancel all or a certain level of log records;
  2. Can be directed to different processors;
  3. Recorder and processor can filter records;
  4. Formatted in different ways;
  5. Multiple loggers can be used;
  6. It is controlled by a configuration file by default, and the configuration can also be replaced by a program.

Basic log

  1. Call the global logger
  2. Cancel: Logger.getGlobal (). SetLevel (Off)

Advanced log

  1. The recorder has a hierarchical structure, and the child inherits the attributes of the parent
  2. 7 levels: SEVERE, WARNING, INFO, CONFIG, FINE, FINER, FINEST, the first three by default

By default, the class name and method name information is recorded, but the VM may not be optimized to obtain accurate calling information. You can use the logp method to obtain the exact information of the calling class and method

effect:

  1. The method used to track the execution flow: entring, exiting
  2. Log unexpected exceptions: throwing, log

Modify the log manager configuration

Default: jre / lib / 1ogging.properties
Modification: java -Djava.util.logging.config.file = configFile MainClass

Modify the log level name. Level = FINE
default log manager: java.util.logging.LogManager
can be modified through system properties: java.util.logging.manager

processor

  • Use ConsoleHandler by default
  • Default INFO level java.uti1.1ogging.ConsoleHandler.level
  • Send to processor and parent processor by default

Other processors: FileHandler, SocketHandler
can modify the default behavior of the file processor

filter

Implement Filter, setFilter method in recorder or processor

format

Implement Formatter, use setFormatter method in processor

Common operations

  1. The logger is named as the main package name
  2. Install the default configuration in the program
  3. Only the logs that are useful to users are set to the first 3 levels, which are displayed on the console.

Debugging skills

  1. Print variables;
  2. Place the main method in the class and unit test each class;
  3. Use JUnit to organize test cases
  4. Use a logging proxy to intercept method calls and record logs
  5. Print stack trace Thread.dumpStack ()
  6. Capture stack trace to string
  7. Capture error information to file java MyProgram 2> errors.txt
    java MyProgram 1> errors.txt 2> & 1
  8. The stack trace of the non-caught exception is saved to a file, and the static Thread.setDefaultUncaughtExceptionHandler method can be called to change the handler of the non-caught exception
  9. To observe the class loading process, you can use the -verbose flag to start the Java virtual machine
  10. The -Xlint option tells the compiler to check some commonly prone code problems
    [External link image transfer failed, the source site may have an anti-theft chain mechanism, it is recommended to save the image and upload it directly (img-Vg4mJ7vS-1582984683851) // 1520493E-927F-420A-8EE1-BA6F74088A9D / appyinxiangcom / 11767354 / ENResource / p3065)]
  11. Support
    Jconsole processID for monitoring and managing Java applications using JVM
  12. jmap utility to get a heap dump
    jmap -dump: format = b, file = dumpFileName processID
    jhat dumpFileName
    into localhost: 7000
  13. Running the Java Virtual Machine with the -Xprof flag will run a basic profiler to track
    the methods that are frequently called in the code

summary

This article sorts out the classification of program errors. In addition to returning special return values, Java language can handle the problems in the program by throwing exception objects and catching exceptions. Record the business and program information in the running of the program through different log levels, and realize the program detection in the program development and testing stages through assertions.

Published 159 original articles · praised 225 · 210,000 views

Guess you like

Origin blog.csdn.net/lyg673770712/article/details/104583090