Java basic Syntax < 11 > Exception Assertion Log debugging

Source: Internet
Author: User
Tags stack trace string format try catch

1 Handling Error 1.1 Exception classification The error class hierarchy describes the internal and resource exhaustion errors of the Java Runtime System. When designing Java programs, the main focus is on the exception hierarchy. Exceptions caused by program errors belong to RuntimeException, and the program itself is not a problem, but exceptions due to problems such as I/O errors are other exceptions. RuntimeException contains the following scenarios:
    • Wrong type conversion classcastexception
    • Array access out of bounds arrayindexoutofboundsexception
    • Access NULL pointer nullpointerexception
    • The specified class does not exist ClassNotFoundException
    • Mathematical operator Exception ArithmeticException
    • Method parameter Error IllegalArgumentException
    • No access to Illegalaccessexception
Exceptions that are not derived domain RuntimeException include:
    • Attempting to read data behind the end of the file
    • Attempt to open a file that does not exist.
    • An attempt was made to look up a class object based on a given string, and the string represented by it does not exist.
1.2 declares that an exception has been checked if it cannot be handled. For example, a piece of code that reads a file knows that a file that is likely to be read does not exist, or the content is empty, so the code attempting to process the file information needs to inform the compiler that it might throw an exception to the IOException class. At the method throws XXXException1.3 how to throw an exception method body throw new xxxexception (); 1.4 Create exception class define a class that derives from the exception or exception subclass definition should contain two constructors one is the default constructor and the other is a constructor 2 with detailed information to catch the exception try catch should usually catch those who know how to handle the exception, and continue to pass on exceptions that do not know how to handle them. Try Catch catch ... Catch multiple exception catch again throws an exception finally, the code in the FINALLY clause is executed regardless of whether an exception is caught. Close the file read stream, use the 3 technique of using exception mechanism when closing resources
    • Exception handling is not a substitute for simple tests using if judgment
    • Do not refine the exception excessively
    • Using exception hierarchies
    • Do not suppress exceptions
    • In detecting errors, it is more demanding than letting go.
    • Don't be ashamed to pass the exception
4 using the assertion assertion mechanism allows you to insert some check statements into your code during testing. Contemporary? When published, these inserted detection statements are automatically moved. An assert condition: An expression in which both forms detect the condition and throw a Assertionerror exception if the result is false. In the second form, the expression is passed into the Assertionerror constructor and converted to a message string. 4.1 Enable and disable assertions by default, assertions are disabled. You can enable it with the-enableassertions or-ea option when you run the program Java–ea Xxapp Note: You do not have to recompile the program when you enable or disable assertions. Enabling or disabling assertions is the function of the ClassLoader. When an assertion is disabled, the ClassLoader skips the assertion code, so it does not slow down the program. You can also use assertion 4.2 in a class or package to complete the parameter check in the Java language, there are 3 mechanisms for handling system errors: Throwing an Exception Log using assertions when to select assertions: Assertion failure is fatal, unrecoverable error, Assertion checking is used only for development and test phase @param A, the array to be sorted (must is not being null) assert a! = null;4.3 for the document assuming that the assertion 5 logging API advantage is used: 1 can easily cancel all day Logging, or simply canceling a level of logging, and opening and closing the operation is easy 2 It is very simple to suppress the output of logging, so it is minimal to leave these log codes in the program. 3 logging can be directed to different processors that are used to display in the console, which are used to store the medium 4 logger and the processor can filter the records. Filters can discard useless record entries based on criteria set by the filter actuator. 5 logging can be formatted in different ways, such as plain text and XML6 applications can use multiple loggers, which use the same hierarchy name as the package name 7 by default, the configuration of the log system is controlled by the configuration file  5.1 The basic log Logger.global The default logger, you can replace it with System.out and log information by invoking the info method. Logger.getglobal (). info ("  ");P S: Automatically contains the time, called Class name and method name, but is called in the appropriate place: Logger.getglobal (). SetLevel (Level.off) ; Will cancel all log 5.2 Advanced log enterprise logs, do not log all logs to a global logLogger, instead, the custom logger calls the GetLogger method to create or retrieve a logger. Like the package name, the logger name also has a hierarchy. 7 Levels of logging            severe            waring           info            config            fine           finer            finest           By default, Record only the first three levels, or use Level.off to close all levels of records.            logger.setlevel (level.fine);            Fine and higher-level records can be recorded.            can use Level.all to turn on all levels of records             Record method: &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&Nbsp;   logger.waring (message);           Logger.fine (message);            Logger.log (level.fine,message);                       The default logging will display the class name and method name that contains the log call, as shown in the stack. However, if the virtual machine optimizes the execution process, it cannot get accurate invocation information. At this point, you can call the Logp method to get the exact location of the calling class and method:           void Logp (level L, String ClassName; String methodname,string message)  5.3 Modify the Log Manager configuration to modify the various properties of the logging system by editing the configuration file. E/lib/loggin.properties to use a different configuration file, set the Java.util.logging.config.file attribute to the location where the configuration file is stored and start the application with the following command java– Djava.util.logging.config.file-config-file MainClass;. level=info 5.4 Localized localized applications contain local-specific information in the resource bundle. The 5.5 processor logger sends the record to the Consolehandler and is output by it to the System.err stream.            by default, the logger sends records to its own processor and parent processor. To send log records elsewhere, add additional processors. The Log API provides Filehandler, and the other is soCkethandler. Sockethandler sends a record to a specific host and port, Filehandler can collect records from the file.            can send records directly to the default file's processor as follows             Filehandler handler = new Filehandler ();            Logger.addhandler (handler);            These records are sent to the Javan.log file in the user's home directory, and N is the unique number of the file.            can also customize the processor by extending the handler or Streamhandler class. 5.6 Filters filter based on logging level you can also customize the filter Boolean isloggable (LogRecord record) by implementing the filter interface and defining the following methods   5.7 The formatter Consolehandler class and the Filehandler class can generate log records in both text and XML format. You can also customize the format, you need to extend the Formater class and overwrite the following method string format (LogRecord record)  5.8 logging description 1 for a simple application, select a logger, and name the logger the same as the application package. 2 The default   log configuration logs all messages with levels equal to or above the info level to the console. Users can override the default configuration file. Messages with 3 levels of info, waring, severe are displayed on the console, and meaningful messages are set to these levels. 6 Debugging Tips
    • 1 use to print any value
    • Put a Main method unit Test in Class 2
    • 3 Junit
    • 4th Log Agent
    • 5 using the Printstacktrace method provided by the Throwable class, you can get stack conditions from any one exception.
    • 6 stack trace displayed on System.err
    • 7 Save the error message in a program in a file
    • 8 It is not a good idea to have a stack trace of a non-catching exception in System.err.
    • 9 You can start the Java Virtual machine with-verbose to observe the loading process of the class
    • The xlint option compiler checks for some common code issues that can be easily seen
    • One-to-one Java Virtual machine support for monitoring and managing Java applications
    • 12 You can use the Jmap utility to get a heap dump that shows each object in the heap.
    • 13 If you run a Java virtual machine using the-XPROF flag, you run a basic profiler to track the methods that are often called in the code.
7 using the debugger in debug, the Step into command tracks the internal Eclipse f5step over command for each method call to the next line, and does not track the internal eclipse F6 of the method call

Java basic Syntax < 11 > Exception Assertion Log debugging

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.