s2/java/06-exception

Source: Internet
Author: User
Tags finally block

Inputmismatchexception is a subclass of Exception.

System.exit (1); End Program Run

If the try statement block encounters an exception during execution, and the exception that is thrown is not declared in the catch block, the program exits immediately.

In the catch block can be added user-defined processing information, you can also call the Exception object method output exception information, commonly used methods are the following two kinds.

void Printstacktrace (); the stack information for the output exception. The stack information includes the execution flow of the program to the current class, which outputs the method call sequence from the method call to the exception throw , asshown in 6.5 . The throwfor () method in the Java.util.Scanner class in this example is where the exception is thrown, while the Main () method in the Test3 class is at the outermost method call.

String GetMessage (): Returns the exception information description string. This string describes the cause of the exception and is part of the printstacktrace () output information.

Table 6-1 Common exception types:

Abnormal

Description

Exception

Root class of an exception hierarchy

ArithmeticException

Arithmetic error scenarios, such as dividing by zero

ArrayIndexOutOfBoundsException

Array subscript out of bounds

NullPointerException

Attempting to access a null object member

ClassNotFoundException

Unable to load the required classes

Inputmismatchexception

The desired data does not match the actual input type

IllegalArgumentException

Method accepted to illegal parameter

ClassCastException

Object coercion type conversion error

NumberFormatException

Numeric format conversion exception, such as converting "ABC" to Digital

Note: Even if a return statement exists in a try block and a catch block , the statements in the finally block are executed , with the order of execution when the exception occurs: Execute a try block or the statement before the return in the catch , executes the statement in the finally block, executes the return in the try block or catch block statement exits.

The only case in which a statement in a Finally block is not executed: Execute System.exit (1) in the exception handling code and exit the Java virtual machine.

When using a multiple catch block, the order of the catch block must be from the subclass to the parent class, and the last general is the Exception class.

The Java language uses the keyword throws to declare various exceptions that a method might throw. Throws can declare multiple exceptions at the same time, separated by commas.

Two ways of handling exceptions:

        1. catch and handle exceptions through Try-catch.
        2. continue declaring exceptions through throws. If the caller does not intend to handle the exception, you can continue to declare the exception through throws , allowing the last-level caller to handle the exception. The exception declared by the main () method will be handled by the Java virtual machine.

In the Java language, you can use the throw keyword to throw an exception yourself.

such as:* * *!!!!!

public void Setsex (String sex) throws exception{

if ("Male". Equals (Sex) | | " Female ". Equals (Sex))

This.sex=sex;

else{

throw new Exception (" gender must be \" " male \" or " female \"!); //*****!!!!!

}

}

The difference between throw and throws is shown in the following 3 aspects:

        1. Different:throw is used to throw an exception in the program;throws is used to declare that an exception was thrown within the method.
        2. Use different location:throw is inside the method body and can be used as a separate statement;throws must follow the list of method parameters and cannot be used alone.
        3. Content is different:throw throws an exception object, and can only be one; throws is followedby an exception class, and can be followed by multiple exception classes.

Exception classification:

Throwable class: All exception types are subclasses of the Throwable class , Throwable is a subclass of Object that derives two subclasses, Error and Exception.

Error class: Represents a critical error that cannot be recovered by the program itself, such as a memory overflow dynamic link failure, virtual machine error. Applications should not throw objects of this type (typically thrown by virtual machines). In the event of such an error, there is no other way than to try to secure the exit of the procedure. Therefore, in the program design, you should pay more attention to the Exception class.

Exception class: non-critical errors thrown and handled by Java applications, such as missing files, network connections or interrupts, arithmetic operation errors (e.g. by 0), array subscript out of bounds, loading a non-existent class, null object manipulation, type conversion exceptions, and so on. Its various subclasses correspond to different types of exceptions.

Run-time exception: Includes runtimeexception and all its subclasses and does not require the program to handle them. Subclasses including arithmeticexception,inputmismatchexception,nullpointerexception,numberformatexception , etc., can not be used in the program Try-catch or throws are processed and can still be compiled and run, and if an exception occurs at runtime, the stack information of the exception is output and the program's operation is terminated.

Checked Exception (non-runtime Exception): Exception class that is inherited by Exception except for runtime exceptions . The program must either catch or declare the exception to be thrown, or a compilation error will occur and cannot be compiled. There are two types of processing: catching and handling exceptions at the current location through Try-catch , throwing exceptions through throws declarations, and handing them over to the upper-level invocation method.

The steps to use log4j in MyEclipse are simple and are divided into the following 4 steps:

(1) Add the JAR file used by log4j in the project .

(2) Create a log4j.properties file.

(3) write the log4j.properties file and configure the log information.

(4) use log4j to log information in the program .

The log is divided into the following 3 categories , depending on the contents of the record:

SQL log: Records the SQL statements executed by the system .

Exception Log: Records the exception events that occurred during system operation.

Business log: Record the system running process, such as user login, operation record.

Note: Thelog4j.properties file must be placed in the src root directory, not in the package!!!

Write The log4j.properties file and configure the log information:

# # # Set Logger output level and output Destination # # #

Log4j.rootlogger=debug, Stdout,logfile

# # # to output log information to the console # # #

Log4j.appender.stdout=org.apache.log4j.consoleappender

Log4j.appender.stdout.target=system.err

Log4j.appender.stdout.layout=org.apache.log4j.simplelayout

# # # to output log information to file: Jbit.log # # #

Log4j.appender.logfile=org.apache.log4j.fileappender

Log4j.appender.logfile.file=jbit.log

Log4j.appender.logfile.layout=org.apache.log4j.patternlayout

Log4j.appender.logfile.layout.conversionpattern=%d{yyyy-mm-dd hh\:mm\:ss}%l%F%p%m%n

The Logger object is a logger used to replace System.out or system.err , for the programmer to output log information, and he provides some column methods to output different levels of log information.

public void Debug (Object msg)

PUBLCI void Debug (Object mes,throwable t)

public void info (Object msg)

public void info (Object msg,throwable t)

public void warn (Object msg)

public void warn (Object msg,throwable t)

public void error (Object msg)

public void error (Object msg,throwable t)

public void Fatal (Object msg)

public void fatal (Object msg,throwable t)

A detailed description of the configuration file log4j.properties:

1. Output Level

Log4j.rootlogger=debug,stdout,logfile

Where debug refers to the output level of the Logger (Logger), the main output level and meaning are as follows.

Fatal: Indicates that a critical error event will cause the application to exit.

Error: Indicates that the system continues to operate without affecting the failure event.

Warn: Indicates a situation in which a potential error occurs.

Info: Indicates the message at a coarse-grained level, emphasizing the application's running process.

Debug: Indicates fine-grained information events that are very helpful for debugging applications.

Each output-level priority:Fatal>error>warn>info>debug

The logger (Logger) will only output information that is above or equal to that level. For example, the level of debugwill output fatal,error,warn,info,debug level log information, and level error, only the fatal,error level log information will be output.

2, day to output destination Appender

Log4j.rootlogger=debug,stdout,logfile

Among them,stdout,logfile refers to the name of the log output destination.

Log4j allows logging to multiple output destinations, and an output destination is called a Appender. There are several Appender in the log4j .

Consoleappender: Output log events to the console. by Configuring the output to System.out or System.err with the target property , the default target is System.out.

Fileappender: Output Log event to a file. the path and name of the file through the profile property.

The example has two Appender, the first named stdout, uses the Consoleappender, writes the log information to the console by configuring the Target property System.err. The second Appender, named logfile, uses fileappender towrite the log information to the specified file by configuring the Files property the Jbit.txt.

3. Log layout type layouts

The Appender must use a layout type layouts associated with it tospecify its output style. the following 3 types of Layout are most commonly used in log4j .

Htmllayout: The formatted log output is an HTML table.

Simplelayout: Format the log output in a very simple way, his output level levels , followed by a dash "--", and finally the log message.

Patternlayout: Formats the log output according to the specified conversion mode, thus supporting a rich variety of output formats. You need to configure layout. The Conversionpattern property, if this property is not configured, uses the default conversion mode.

The first Appender in the example is stdout, simplelayout is used, and the second Appender is logfile, using the Patternlayout, you need to configure layout. The Conversionpattern property customizes the output format.

4. Conversion Mode Conversionpattern

For patternlayout, you need to configure layout. Conversionpattern Properties, common configuration parameters and meanings are as follows.

%d: the date and time used to set the output log, the default format is ISO8601. You can also specify the format later, such as %d{yyyy-mm-dd HH:mm:ss}, the output format is similar to 2010-03-09:

%m: Used to output the message specified in the code.

%n: Used to output a carriage return line break.

%l: Used to output where the log event occurred, including the class name, the thread that occurred, and the number of rows in the code. For example, if the output is cn.jbit.log.Test11.main (test.java:21), the log event occurs in the Main of the Test11 class under the Cn.jbit.log package. thread, the number of lines in the code is line .

%p: Used to output priority, that is, debug,info,warn,error,fatal and so on.

%F: Used to output file names.

%M: Used to output the method name.

S2/java/06-Exception

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.