Dark Horse Programmer--java Foundation--Exception handling

Source: Internet
Author: User
Tags finally block

--java Training, Android training, iOS training,. NET training look forward to sharing with you! ——

Exception handling

1. Exception Handling Overview 1.1. Using the return value status to identify the exception

Prior to the advent of the Java language, traditional exception handling methods used the return value to identify the exception of the program, although familiar to programmers, but there are many disadvantages.
First, an API can return any return value, and the return value itself does not explain whether the return value represents an exception condition and the specifics of the exception, and the program that calls the API itself judges and interprets the meaning of the return value.
Secondly, there is no mechanism to ensure that exceptions will be handled, the caller can simply ignore the return value, the programmer needs to call the API to remember to detect the return value and handle the exception condition. This approach also makes the program code verbose, especially when the IO operation is prone to exceptions such as processing, a large part of the code to handle the exception of the switch branch, program code readability becomes poor.

1.2. Exception handling mechanism

When an exception is thrown in the program, the program jumps out of the code that caused the exception in the program, the Java Virtual machine detects the catch block that handles the exception that matches the Try keyword, and, if found, the code in the catch block, then proceeds to execute the program. The code for the exception that occurred in the try block is not re-executed. If no catch block is found to handle the exception, the current thread that encounters the exception is aborted after all the finally block code is executed and the Uncaughtexception method of the Threadgroup that belongs to the current thread is called.

2. Handling and capturing of exceptions 2.1. Throwable,error and exception

There are throwable classes defined in the Java exception structure, and Exceotion and error are the two subclasses of their derivation. Where exception represents an exception due to network failure, file corruption, device errors, illegal user input, and so on, this type of exception can be handled through the Java exception capture mechanism. Error indicates errors in the Java Runtime environment, such as JVM memory overflow, and so on.

2.2. Try-catch

The try {...} statement specifies a piece of code that is the scope for capturing and handling exceptions at once. During execution, the code may produce and throw one or more types of exception objects, which are followed by a catch statement that handles each of these exceptions accordingly.
If there is no out-of-column generation, all catch code snippets are skipped and not executed
In a catch statement block is the code that handles the exception. The exception pair declared in the catch (catch (Someexception e)) encapsulates the information that occurs with the exception event, and some methods of this object can be used in the CATCH statement block to obtain this information
Common formats:

...try{//可能出现异常的代码片段}catch(Exception e){//处理该异常的代码片段}...
2.3. Multiple catch

Each try statement block can accompany one or more catch statements to handle the different types of exceptions that may occur. The order in which catch exception types are caught from top to bottom should be subclasses to the parent class.
For example

try{            …}catch(NullPointerException e){//子类异常应在上面捕获            …}catch(RuntimeException e){//父类异常在下面捕获          …    }catch(Exception e){//应养成最终捕获Exception的习惯          …}

Typically, when writing code, we should capture exception in the last catch, which guarantees that the code will not fail because of an exception that is not declared in the catch, causing the program to terminate.

2.4. The role of finally

The finally statement provides a unified exit for exception handling, allowing the state of the program to be managed uniformly before the control process is transferred to the rest of the program.
The code specified by finally is executed regardless of whether the block specified in the try is thrown or not, usually in the finally statement, such as closing open files, deleting temporary files, and so on.
A finally statement block can only be defined once after a try statement block, or after the last catch statement block.

2.5. Throw keyword

When the program is unable to process an error, it throws the corresponding exception object, in addition, at some point, you may want to throw an exception, such as after the end of the exception processing, then throw the exception, let the next layer of exception processing block to catch, if you want to throw the exception, you can use the "throw" keyword, and generates the specified exception object.
For example:

thrownewArithmeticException();

2.6. Throws keywords

Many methods are declared in the program, which may throw exceptions due to some errors, but you do not want to handle these exceptions directly in this method, and you want to call this method to unify processing, you can use the "throws" keyword to declare this method will throw an exception
For example:

void stringToDate(String str)throws ParseException{             ……}
2.7. Throws when overriding a method

When using inheritance, it is declared on a method of the parent class that throws throws some exceptions, and when the method is heavier in a subclass, we can do the following:
Exception not handled (throws not declared when overriding method)
Partial exceptions declared in the parent class can be declared in throws only
Subclass exceptions for exceptions thrown in parent class methods can be declared in throws
However, you cannot do the following:
An extra exception is thrown when overriding a method in a throws declaration
The overriding method is to declare the parent exception of the thrown exception declared in the parent class method in throws

3. Java exception API3.1. RuntimeException

Java exceptions can be classified as detectable exceptions, non-detection exceptions
Detectable exceptions: Detectable exceptions are validated by the compiler, and for any method that declares an exception, the compiler enforces a processing or declaration rule, does not catch the exception, and the compiler does not allow compilation
Non-detection exceptions: Non-detection exceptions do not follow processing or claim rules. When such an exception is generated, it is not necessary to take any appropriate action, and the compiler does not check whether such an exception has been resolved
The RuntimeException class is a non-detection exception, because runtime exceptions caused by ordinary JVM operations can occur at any time, and such exceptions are typically raised by specific operations. However, these operations occur frequently in Java applications. Therefore, they are not restricted by the compiler's checking and processing or declaring rules.

3.2. Common RuntimeException

IllegalArgumentException
The exception thrown indicates that an invalid or incorrect argument was passed to the method
NullPointerException
Thrown when an application attempts to use null where the object is needed
ArrayIndexOutOfBoundsException
This exception is thrown when an array subscript is used that exceeds the allowable range of the array
ClassCastException
This exception is thrown when an attempt is made to cast an object to a subclass that is not an instance
NumberFormatException
This exception is thrown when an application attempts to convert a string to a numeric type, but the string cannot be converted to the appropriate format.

4. Exception commonly used API4.1. Printstacktrace

Throwable defines a method that can output error messages to track the contents of the stack when an exception event occurs. The method is defined as:
void printStackTrace()
For example:

try{            …}catch(Exception e){            e.printStackTrace();//输出执行堆栈信息 }
4.2. GetMessage

A method is defined in Throwable to get information about an exception event. The method is defined as:

StringgetMessage()
For example:

try{            …}catch(Exception e){            System.out.println(e.getMessage());}
4.3. Getcause

Many times, when an exception is thrown by another exception, the Java library and open source will wrap an exception in another exception. At this point, logging and printing root exceptions become very important. The Java exception class provides the Getcause () method to retrieve the cause of the exception, which can provide more information about the cause of the root level of the exception. This Java practice is a great help in debugging or troubleshooting your code. In addition, if you want to wrap an exception into another exception, a new exception will be constructed to pass the source exception.

Throwable getCause()
Gets the reason that the exception occurred

5. Custom Exception5.1. The meaning of custom exceptions

Java exception mechanisms ensure that programs are more secure and robust. Although the Java class Library already offers many classes that can handle exceptions directly, it is sometimes necessary for developers to customize exceptions to capture and handle exceptions more accurately to provide a better user experience.

5.2. Inheriting exception custom exceptions

To create a custom exception class, syntax format:

publicclass[自定义异常类名]extendsException{            …}
5.3. How to write a construction method

When a custom exception is defined, we can generate the appropriate construction method from eclipse.
The steps are as follows:
① declares a class and inherits from exception
② Right click on source
③ Select generate constructors from superclass
④ confirm build after all construction methods in the parent class are selected
For example:

publicclass MyException extends Exception{publicMyException(){super();// TODO Auto-generated constructor stub}publicMyException(String message, Throwable cause){super(message, cause);// TODO Auto-generated constructor stub}publicMyException(String message){super(message);// TODO Auto-generated constructor stub}publicMyException(Throwable cause){super(cause);// TODO Auto-generated constructor stub}}

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Black Horse Programmer--java Base-Exception handling

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.