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:
- User input
- Physical restrictions
- device
- 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
- Call a method that throws the checked exception
- An error was found during the running of the program, and a checked exception was thrown using the throw statement
- The program has an error and throws an unchecked exception
- 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
- Find the appropriate exception class
- Create exception class object
- 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
- Exception handling cannot replace simple tests
- Don't over-refine the exceptions and make the code bloat
- Leverage exception hierarchy
- Don't suppress abnormal
- When detecting errors, harshness is better than laissez-faire (throw early)
- 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
-
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. -
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
- 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:
- It is easy to open, cancel all or a certain level of log records;
- Can be directed to different processors;
- Recorder and processor can filter records;
- Formatted in different ways;
- Multiple loggers can be used;
- It is controlled by a configuration file by default, and the configuration can also be replaced by a program.
Basic log
- Call the global logger
- Cancel: Logger.getGlobal (). SetLevel (Off)
Advanced log
- The recorder has a hierarchical structure, and the child inherits the attributes of the parent
- 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:
- The method used to track the execution flow: entring, exiting
- 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
- The logger is named as the main package name
- Install the default configuration in the program
- Only the logs that are useful to users are set to the first 3 levels, which are displayed on the console.
Debugging skills
- Print variables;
- Place the main method in the class and unit test each class;
- Use JUnit to organize test cases
- Use a logging proxy to intercept method calls and record logs
- Print stack trace Thread.dumpStack ()
- Capture stack trace to string
- Capture error information to file java MyProgram 2> errors.txt
java MyProgram 1> errors.txt 2> & 1 - 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
- To observe the class loading process, you can use the -verbose flag to start the Java virtual machine
- 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)] - Support
Jconsole processID for monitoring and managing Java applications using JVM - jmap utility to get a heap dump
jmap -dump: format = b, file = dumpFileName processID
jhat dumpFileName
into localhost: 7000 - 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.