Thinking in Java Note 12 exception

Source: Internet
Author: User
* ** Basic Concepts

The advantage of exceptions is that they can often reduce the complexity of error handling code. If exceptions are not used, specific errors must be checked and processed in many places of the program. When an exception is used, you do not need to check the method call because the exception mechanism can capture this error and only need to handle it in one place. Besides, the execution process code and error handling code can be separated.
*** Checked vs unchecked exceptionExcept for error and runtimeexception, you need to care about the remaining exceptions. These exception classes are collectively referred to as checked exceptions. As for error and runtimeexception, they are collectively referred to as unchecked exceptions.
* ** When an exception is thrown, Java uses new to create an exception object on the stack. Then, the current execution path is terminated and a reference to the exception object pops up from the current environment. At this time, the exception handling mechanism takes over the program and starts to find an appropriate place to continue executing the program, this is an exception handling program. Its task is to restore the program from the error state so that the program can either run in another way or continue running. Exceptions allow us to consider everything as a transaction. Exceptions can take care of the bottom line of these transactions. One of the most important aspects of exceptions is that if a problem occurs, we will not allow the program to continue along its normal path.
* ** The exception indicates that the client programmer should be informed of the exceptions that may be thrown by the method. Use ThrowsKeywords

     void B() throws NewException{
throw new NewException();
}

* ** The log information can be automatically recorded in the custom exception categories of exception logs;

class LoggingException extends Exception {
private static Logger logger = Logger.getLogger("LoggingException");

public LoggingException() {
StringWriter trace = new StringWriter();
printStackTrace(new PrintWriter(trace));
logger.severe(trace.toString());
}
}
In more cases, it is not a custom exception class, but an exception of others. The log recording method is as follows:

public class LoggingExceptions2 {
private static Logger logger = Logger.getLogger("LoggingExceptions2");

static void logException(Exception e) {
StringWriter trace = new StringWriter();
e.printStackTrace(new PrintWriter(trace));
logger.severe(trace.toString());
}

public static void main(String[] args) {
try {
throw new NullPointerException();
} catch (NullPointerException e) {
logException(e);
}
}
}


* ** Re-throw an exception. If you only re-Throw the current exception object, printstacktrace () displays the call stack information of the original exception throw vertex rather than the information of the re-throw vertex. To update this information, you can useThrow(Exception) E. fillinstacktrace ();
* ** The exception chain throws another exception after capturing an exception and saves the original exception information, which is called the exception chain. In the throwable subclass, the three basic exception classes provide constructors with the cause parameter (error exception runtimeexception). For other types of exceptions, the initcause () method should be used.
* ** Java standard exception throwable objects can be divided into two types: Error indicates Compilation Time and system error. Exception is a basic type that can be thrown.
* ** Runtimeexception runtime exceptions (including runtimeexception and its subclasses) (not checked exceptions) are automatically thrown by the Java virtual machine, so they do not need to be listed in the exception description. This exception is an error and will be automatically captured. If runtimeexception is not captured and goes directly to main (), the abnormal printstacktrace () method will be called before the program exits. Runtimeexception indicates a programming error: 1 unexpected error, such as a null reference passed out of the control range. 2. errors that should be checked in the code.
* ** Finally usage: Restores resources other than memory to the initial state, such as open files or network connections, graphics drawn on the screen, and external world switches. Exception loss: the exception should not be ignored. However, it can be easily ignored. Before the exception thrown in try is not caught, if an exception is thrown in finally, the previous exception will be overwritten, resulting in the loss of the previous exception. Return from finally can also cause loss of exceptions (using the return method in finally will cause silence to throw all exceptions ).
* ** Exceptions are restricted in the inheritance structure. The subclass constructor must contain the exception Declaration of the parent constructor. The constructor of the derived class cannot catch exceptions thrown by the base class constructor. The exception declaration of the method covered by the subclass must be a subset of the exception Declaration of the parent class (or a derived class exception declared by the parent class ). Object replacement is guaranteed.
* ** When a constructor exception occurs, make sure that everything is cleared correctly. However, an exception may occur within the constructor, and the initialization action has not been completed yet. Therefore, the constructor cannot clean up the constructor. The usual method of cleaning is to immediately enter a try-Finally block after creating the object to be cleaned up, even if the constructor does not throw an exception, it should also be used. For example:

     public class Cleanup {
public static void main(String[] args) {
try {
InputFile in = new InputFile("Cleanup.java");
try {
String s;
int i = 1;
while ((s = in.getLine()) != null )
; // Perform line-by-line processing here...
} catch (Exception e) {
System. out .println("Caught Exception in main");
e.printStackTrace(System. out );
} finally {
in.dispose();
}
} catch (Exception e) {
System. out .println("InputFile construction failed");
}
}
}

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.