Java Exception Handling

Source: Internet
Author: User

Java Exception handling error handling error

Errors always occur during the execution of a computer program:

L User Input Error

l Read and write file errors

L network error, memory exhausted, unable to connect printer

If the method call is faulted, how the caller learns about the error:

L Convention return error code

Abnormal

Java uses exceptions to represent errors:

L exception is class, itself with type information

L Exceptions can be thrown anywhere

l Exceptions only need to be captured in the upper layer, and the method is transferred

Java's exception system

The Java exception itself is class

L Throwable

N Error

N Exception

U runtimeexception

U ioexception

Exceptions that must be caught:

Includes Exception and its subclasses, but excludes RuntimeException and its subclasses, called checked Exception

Exceptions that do not need to be caught:

L Error and its sub-categories

L RuntimeException and its sub-categories

Why does Java need to define such an exception system?

Error is a serious error, the program is generally powerless to

Exception is a run-time logic error that should catch the exception and handle

Catching exceptions

L use Try...catch to catch exceptions

L The statement of possible exception is placed in try{}

L use catch to capture corresponding exception and its subclasses

You can use multiple catch clauses:

L each catch captures the corresponding exception and its subclasses

L match from top to bottom, match to a catch and no longer match

L subclass must be written in front

Finally

The finally statement block guarantees that there are no errors to be performed

Finally, it's not necessary.

Finally is always the last to handle

Multi-Catch

If some exceptions have the same processing logic:

There is no inheritance relationship, you must write multiple catch statements

You can use | to represent multiple exception

Must jdk>=1.7 above

declaring exceptions

Method calls to checked exception that might be thrown

L Capture Exception and process

L do not capture but pass throws declaration

L still need to capture the upper layer through the THORWS declaration

L main () is the last chance to capture exception

Propagation of exception exception thrown

When a method throws an exception:

L If the current method is not captured, the exception is thrown to the upper call method

L until a try...catch is caught.

L printstacktrace () can print out the call stack of the method

Throw exception

How to throw an exception:

L Create an instance of a exception

L Throw with throw statement

Conversion exception

If a method catches an exception and throws a new exception in the catch clause, it is equivalent to converting the thrown exception type:

The new exception loses the original exception information, so the original exception's instance E is passed into the new exception

Throw exception

If an exception is thrown in the catch clause, before the exception is thrown:

L Finally statement guarantees execution

L If we throw an exception in the finally statement, then the exception of the original catch is no longer thrown

L An exception that is not thrown is called a masked exception (suppressed exception)

Java exception propagation can propagate only one exception, which throws the front and is not overwritten by a catch

Suppressed

How do I save all the exception information?

L Save original exception with Origin variable

L Add a new exception with addsuppressed () if the original exception exists

L If there is an original exception, or a new exception, and finally throws

L use getsuppressed () to get all suppressed exception

L jdk>=1.7

Custom exceptions

Custom exceptions should be derived from the appropriate exception

Recommended Runtimeexcrption

Custom exceptions should provide multiple construction methods

Assertion and Log Assertion

Assertion is a method of debugging a program

l Use the Assert keyword

L assertion condition expected to be true

L If the assertion fails, throw Assertionerror

L Optional Assertion Message

Assert x >= 0: "x must >= 0";

Characteristics

L Throw Assertionerror when assertion fails, cause program to end exit

L cannot be used for recoverable program errors

L should only be used for development and testing phases

What is recoverable error: If we consider a program error to be recoverable, for example: whether a variable is empty

For recoverable program errors:

L should not use assertions

L should throw an exception in the upper layer capture

Enable assertion

JVM shuts down assertion directives by default

To pass the-ea parameter to the Java Virtual machine enable assertion

You can specify a specific class to enable assertions:-ea: Full package name + class name

You can specify a specific package to enable assertions:-ea: Full package name ... (Note Last add three points)

Assertions are seldom used and better methods of writing unit tests.

Java Log Logging

To replace System.out.println ()

You can set the output style

Output levels can be set to prohibit certain levels of output

Can be redirected to a file

Log levels can be controlled by package name

JDK Logging

7 log levels are defined:

SEVERE

WARNING

INFO

CONFIG

FINE

Finer

FINEST

Limitations

The JVM reads the configuration file at startup and finishes initialization

L cannot modify configuration after JVM startup

l need to pass parameters when JVM starts

-djava.util.logging.config.file = Config-file-name

Commons Logging

is a log module created by Apache

L can connect different log systems

L can specify the attached log system through the configuration file

L automatically search and use log4j

L If log4j is not found, use JDK Logging (jdk>=1.4)

6 log levels are defined:

FATAL

ERROR

Warinng

INFO

DEBUG

TRACE

Using log4j

Log4j currently the most popular log framework

L 1.x log4j

L 2.x log4j2

Because Commons Logging preferred to use log4j

We recommend that you always use the Commons logging interface to write logs

No need to introduce log4j during the development phase

Using log4j requires putting the correct configuration file and the associated jar package into the Classpath

Flexibility to modify logs with configuration files, no code changes

Java Exception Handling

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.