The use of exception handling and logging (log4j as an example) in Java

Source: Internet
Author: User
Tags throwable try catch log4j

Exceptions for Java

base class for all exceptions and errors in 1.Java: Throwable
Throwable
Error Exception
(Exception at check-in) (Run-time exception)
RuntimeException
Exceptions in 2.Java are divided into run-time exceptions and check-time exceptions

A run-time exception is a representation of runtimeexception and all subclasses that are not captured in the program and are mostly controlled by code to avoid

Check-in exception: all exceptions except RuntimeException and all of its subclasses must be captured in the program.

The first processing mechanism for exceptions--using Try-catch for exception trapping

1. Use a try block to wrap potentially abnormal code, using multiple catch blocks to handle different exceptions

When a program in a try block has an exception, it goes into the corresponding catch block and no longer executes the code in the try block

After catching an exception with Try-catch, the program will not be blocked if an exception occurs

2. Catch blocks can have more than one, usually ending with catch (Exception e), which means catching all exceptions
But multiple catch block order must be from small to large

3.e.getmessage (): Get the error message
E.printstacktrace (); Printing stack Information

4.try catch Structure If you need to ensure that the program is not interrupted, you must make sure that the program block captures any exceptions that may occur in the program (Finally, with catch (Exception e))

5.finally represents a statement that must be executed regardless of whether the program has an exception, even if there is a return statement in the try block that must finish finally to end the current method.

But using System.exit (0), exiting the program, will no longer execute the finally statement

Therefore, the finally is typically used for operations such as closing the stream, releasing the resource, etc.

6.try-finally can be combined to exist, not necessarily include catch
Indicates that an exception occurred without action, but the code in the finally must execute

The second processing mechanism of exception--throwing mechanism

1. If an exception occurs in the method body, you can use throws to throw on the method declaration without Try-catch capture
Thrown after the method is called, if the capture can continue to throw
In principle, exception handling must be done in the main method, and if it continues to be thrown, it will cause the program to become abnormal and cannot be found

2.throws If you throw more than one exception, you can use commas to separate

3.throw Throwing Exceptions manually in the program

throw new IOException ("Enter age is not legal");

4. If using throw throws a check-type exception, you must use throws on the method body to throw the declaration

If you throw a run-time exception with throw, you no longer have to use throws to throw the declaration.

Instance code:

Try {    setage ( ioexception e) {       e.printstacktrace ();}  Public Static void setage (intthrows  ioexception{    if(i<0| | i>100) {        thrownew IOException ("Enter age is not legal");}    }

How to customize Exception classes

The custom exception class must inherit the existing exception class.
Typically, exception or runtimeexception are inherited, respectively, to declare a check-time exception and a run-time exception.

Instance code:

classAgeexceptionextendsexception{PrivateString message=NULL;  Publicageexception () {} Publicageexception (String message) { This. message=message; }     PublicString getMessage () {returnmessage; }}classAgeruntimeexceptionextendsruntimeexception{PrivateString message=NULL;  Publicageruntimeexception () {} Publicageruntimeexception (String message) { This. message=message; }     PublicString getMessage () {returnmessage; }}

Use of log4j
1. Import Log4j-1.2.17.jar

2. Under the SRC directory peer, create the log4j.properties configuration file

3. In the class that needs to print the log, get a Log object by Logger.getlogger (), and the parameters pass into this class. class

4. Use log objects to call different levels of print statements to log output!
Log.debug ("Print a debug Message");
Log.info ("Print an info");
Log.warn ("Print a warn message");
Log.error ("Print an error message");


Configuration file for log4j log4j.properties

#log4j. rootlogger represents the root configuration. #log4j. Rootlogger=[level], appenderName1, appendername2#level indicates the levels that can be written to the log: #ERROR> WARN > INFO >The DEBUG #设置info indicates that the level is greater than info can be a number of options after the # level of log output, indicating the name of multiple adapters, the name of the adapter can be arbitrarily Log4j.rootlogger=info, logfile,a,b# the configuration of each adapter. Log4j.appender. Adapter name #[appender Specify log output DESTINATION] #org. Apache.log4j.ConsoleAppender (console), # Org.apache.log4j.FileAppender (file), #org. Apache.log4j.DailyRollingFileAppender (Generate a log file every day), # Org.apache.log4j.RollingFileAppender (creates a new file when the file size reaches the specified size) log4j.appender.a=org.apache.log4j.consoleappender# Sets the statement that the console prints. System.out/System.errlog4j.appender.a.target=system.err# which layout to use for log display: # org.apache.log4j.HTMLLayout (layout in HTML table), # Org.apache.log4j.PatternLayout (flexibility to specify layout mode), # Org.apache.log4j.SimpleLayout (contains the level of log information and information string), # Org.apache.log4j.TTCCLayout (contains information about the time, thread, category, and so on that the log produced) Log4j.appender.a.layout=Org.apache.log4j.SimpleLayoutlog4j.appender.logfile=org.apache.log4j.fileappender# The address of the settings file Log4j.appender.logfile.File=Mylog.loglog4j.appender.logfile.layout=org.apache.log4j.patternlayout# sets the style for patternlayout. #%the message specified in the M output code #%P-Output priority, i.e. Debug,info,warn,error,fatal #%r output The number of milliseconds to output the log information from the app startup #%c output belongs to the class, which is usually the full name of the class #%T output the name of the thread that generated the log event #%n outputs a carriage return newline character, the Windows platform is "\ r \ n" and the UNIX platform is "\ n" #%d the date or time of the output log time, the default format is ISO8601, can also be specified after the format, such as:%d{yyy MMM dd HH:mm:ss, SSS}, output similar: October 18, 2002 22:10:28, 921#%l where the output log event occurs, including the class name, the thread that occurred, and the number of rows in the code. Example: Testlog4.main (testlog4.java:10) Log4j.appender.logfile.layout.ConversionPattern=%d{yyyy-mm-dd HH:mm:ss}%l%F%p%m%n# for the current adapter, specifying a separate level that can override the Rootlogger configuration Log4j.appender.logfile.Threshold=warn# Indicates whether to empty the log file when writing to a new log; False to empty the original file, true to append a new log after the original file Log4j.appender.logfile.Append=false

The use of exception handling and logging (log4j as an example) in Java

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.