Java Exception Handling

Source: Internet
Author: User
Tags finally block stack trace thread class throw exception throwable

I. Basics of Java Exceptionsexceptions are errors in the program , but not all errors are exceptions, and errors can sometimes be avoided. For example, your code is missing a semicolon, then running out of the result is the hint is error java.lang.Error; If you use System.out.println (11/0), then you are because you use 0 to do the divisor, Throws a Java.lang.ArithmeticException exception. Some exceptions need to be handled, others do not need to be captured, and are discussed in detail later. The sky is rainy, people have unforeseen, Java program code is also the case. In the process of programming, we should avoid errors and anomalies as much as possible, and how to deal with the unavoidable and unpredictable situations when considering the occurrence of anomalies. Exceptions in Java are represented by objects. Java's handling of exceptions is handled by exception, with different categories of exceptions, each of which corresponds to a type (class), and each exception corresponds to an exception (Class) object. where does the exception class come from? There are two sources, one is the basic exception type defined by the Java language itself, and the other is the exception that the user defines by inheriting the exception class or its subclasses. The Exception class and its subclasses are a form of throwable that identifies the conditions that a reasonable application wants to capture. where does the exception object come from? There are two sources, one is the Java Runtime environment automatically throws system generated exceptions, regardless of whether you are willing to capture and processing, it will always be thrown! For example, an exception with a divisor of 0. The second is the exception that the programmer throws himself, which can be defined by the programmer itself, or it can be defined in the Java language, and throws an exception with the Throw keyword, which is often used to report some information about the exception to the caller. exceptions are for methods, and throwing, declaring throwing, catching, and handling exceptions are all done in the method. Java exception Handling is managed by 5 keyword try, catch, throw, throws, finally. The basic process is to wrap the statement that you want to monitor with a try statement block, and if an exception occurs within a try statement block, the exception is thrown, your code can catch the exception in the Catch statement block, and the exception that is generated by some system is automatically thrown in the Java runtime. You can also declare the method to throw an exception by using the throws keyword on the method, and then throw the exception object through a throw inside the method. The finally statement block executes before the method executes a return, and the general structure is as follows:
try{
Program code
}catch (Exception type 1 exception variable name 1) {
Program code
}catch (Exception type 2 exception variable name 2) {
Program code
}finally{
Program code
}a catch statement can have more than one exception, which matches more than one of the above, and executes the CATCH statement block only when the exception on the match is executed. The type of catch is defined in the Java language or is defined by the programmer itself, indicating that the code throws an exception, the exception variable name represents the reference to the object that throws the exception, and if the catch catches and matches the exception, then the exception variable name can be used directly. At this point the exception variable name points to the matching exception and can be referenced directly in the catch code block. This is very, very special and important! The purpose of Java exception handling is to improve the robustness of the program, you can give the program a remediation opportunity in the catch and finally code block, so that the program does not terminate due to an exception or changes outside the process. At the same time, by obtaining the Java exception information, but also for the development and maintenance of the program to provide a convenient, generally through the exception information can quickly find the problem (code) where the exception. Java exception Handling is a major feature of the Java language, but also a difficult one, mastering exception handling can make the written code more robust and easy to maintain. ii. Java Exception class diagramHere are the hierarchical graphs of these classes:
Java.lang.Object
Java.lang.Throwable
Java.lang.Exception
Java.lang.RuntimeException
Java.lang.Error
Java.lang.ThreadDeathThe following four classes are introduced from the Java API documentation. 1, Throwable
The Throwable class is a superclass of all errors or exceptions in the Java language. a Java Virtual machine or Java Throw statement can only be thrown if the object is an instance of this class (or one of its subclasses). Similarly, only one of this class or its subclasses can be a parameter type in a catch clause. instances of two subclasses, Error, and Exception, are typically used to indicate an abnormal condition has occurred. Typically, these instances are newly created in the context of the exception and therefore contain relevant information (such as stack trace data). 2, Exception
the Exception class and its subclasses are a form of throwable that identifies the conditions that a reasonable application wants to capture, indicating the exceptions that the program itself can handle. 3. Error
error is a subclass of Throwable that represents a serious problem that cannot be recovered by the program itself , and is used to indicate that a reasonable application should not attempt to capture a serious issue. during the execution of this method, there is no need to declare in the method any subclasses of the Error that might have been thrown but not captured by throws, because the Java compiler does not check it, that is, when such an exception may occur in the program, even if it is not captured with the Try...catch statement, Nor does it use the throws sentence declaration to throw it, or it will be compiled through. 4, RuntimeException
RuntimeException is a superclass of exceptions that might be thrown during the normal operation of a Java virtual machine. The Java compiler does not check it, that is, when such an exception may occur in the program, even if it is not captured with the Try...catch statement, it is not thrown with the throws sentence declaration, or it is compiled through, This exception can be avoided by improving the code implementation. 5, Threaddeath
When you call the Stop method with the 0 parameter in the thread class, the victim thread throws an Threaddeath instance. an instance of this class should only be captured if the application must be purged after it has been terminated asynchronously. If the Threaddeath is captured by a method, it is important to re-throw it, because that will allow the thread to actually terminate. If Threaddeath is not captured, the top-level error handler does not output messages. Although the Threaddeath class is "normal", it can only be a subclass of Error and not a subclass of Exception, because many applications capture all occurrences of Exception and then discard them. the above is a simple introduction to the exception API, the usage is very simple, the key is to understand the principle of exception handling, the specific use of the Java API documentation. Third, Java exception handling mechanism
There are two ways to handle code that might appear to be an exception:
First, in the method to catch and handle the exception with the Try...catch statement, the Catach statement can have multiple, to match multiple exceptions. For example:
Public void P (int x) {
try{
...
}catch (Exception e) {
...
}finally{
...
}
} Second, for exceptions that cannot be handled or exceptions to be transformed, an exception is thrown through the throws statement at the declaration of the method. For example:public void Test1 () throws myexception{
...
if (...) {
throw new MyException ();
}
} if each method is simply throwing an exception, the Java virtual Opportunity in the multi-layered nested invocation of the method invocation method is searched back from the method code block in which the exception occurred until a block of code handling the exception is found. The exception is then handed to the appropriate catch statement for processing. If the Java virtual machine goes back to the bottom of the method call stack, the main () method, if you still do not find a code block to handle the exception, follow these steps:
First, the Printstacktrace () method of the object that called the exception prints the exception information for the method call stack.
Second, if the thread that has the exception is the main course, the entire program terminates, and if it is not the main thread, the other thread continues to run. through analysis, we can see that the earlier the processing of abnormal consumption of resources and time, the smaller the scope of the impact. Therefore, do not throw exceptions that you can handle to the caller. Also, it is important not to overlook the code that the finally statement must execute in any case, which guarantees the reliability of the code that must be executed in any case. For example, when a database query is abnormal, you should release the JDBC connection and so on. The finally statement executes before the return statement, regardless of its precedence, or whether the try block has an exception. The only case where the finally statement is not executed is that the method executes the System.exit () method. The role of System.exit () is to terminate the currently running Java virtual machine. A finally statement block cannot change the return value of a return by assigning a new value to the variable, and it is also recommended that you do not use the return statement in the finally block, which is meaningless and prone to errors. Finally, you should pay attention to the syntax rules for exception handling:
The first, try statement can not exist alone, and catch, finally make up try...catch...finally, Try...catch, try...finally Three kinds of structure, catch statement can have one or more, The finally statement has at most one, and the try, catch, finally three keywords cannot be used alone. the scope of the variables in the second, try, catch, finally three blocks of code is independent and cannot be accessed from one another. If you want to be accessible in three blocks, you need to define the variables outside of those blocks. third, multiple catch blocks, when a Java virtual opportunity matches one of the exception classes or its subclasses, executes the catch block without executing another catch block. The throw statement is not allowed to follow the other statements, since these do not have a chance to execute. Fifth, if a method invokes another method that declares an exception, the method either handles the exception or throws the declaration. How can you tell if a method might be abnormal? in general, the method declaration uses the throws statement, the method has a throw statement, method invocation method declaration has the throws keyword. The difference between the throw and throws keywords
throw is used to throw an exception in the method body. The syntax format is: Throw exception object.
Throws is used to declare what exceptions the method might throw, after the method name, the syntax format is: throws exception type 1, exception type 2 ... Exception type N.
Iv. How to define and use exception classes 1, use the existing exception class , if for IOException, SQLException. try{
Program code
}catch (IOException IoE) {
Program code
}catch (SQLException Sqle) {
Program code
}finally{
Program code
} 2. Custom exception Classes
Creating a subclass of exception or runtimeexception will give you a custom exception class. For example:
Public class MyException extends exception{
Public myexception () {}
Public MyException (String SMG) {
Super (SMG);
}
} 3. Using a Custom exception
declaring a method with throws may throw a custom exception, and throw a custom exception in the appropriate place with a throw statement. For example:throws an exception in a certain condition
Public void Test1 () throws myexception{
...
if (...) {
throw new MyException ();
}
} Transform anomalies (also called translations), making exceptions easier to read and easy to understand
public void Test2 () throws myexception{
...
try{
...
}catch (SQLException e) {
...
throw new MyException ();
}
}There is also a code that is interesting:
public void Test2 () throws myexception{
...
try {
...
} catch (MyException e) {
Throw e;
}
}
This code actually catches the exception, and then come clean, there is no point, if there is nothing to deal with, do not deal with the line, directly before the method with the throws declaration is thrown. The catch of the anomaly is going to be done with some meaningful processing. v. Run-time exceptions and check exceptions
The exception class can be divided into two types: run-time exceptions and checked exceptions.
1. Run-time exception
The RuntimeException class and its subclasses are called run-time exceptions, and the exception is characterized by the Java compiler not checking it, that is, when such an exception can occur in a program, even if it is not captured with a try...catch statement, it is not thrown with the throws clause declaration , or it will be compiled through. For example, a Java.lang.ArithmeticException exception is thrown when the divisor is zero. 2. Check Exception
In addition to the RuntimeException class and its subclasses, other exception classes and their subclasses belong to the checked exception, which is characterized either by try...catch capture processing or by a throws statement declaration, or the compilation does not pass. 3, the difference between the two
A run-time exception indicates an exception that cannot be resumed by the program, and the cause of this exception is usually due to an incorrect operation. Once an error occurs, it is recommended that the program be terminated.
A check exception indicates an exception that the program can handle. If the method that throws the exception itself does not handle it or cannot handle it, then the caller of the method must handle the exception, otherwise the call will go wrong and the compilation will fail. Of course, both of these exceptions can be caught and processed by a program, such as a zero-divisor run-time exception:public class HelloWorld {
public static void Main (string[] args) {
System.out.println ("Hello world!!!");
try{
System.out.println (1/0);
}catch (ArithmeticException e) {
System.out.println ("divisor is 0!");
}
System.out.println ("Divisor is zero after the program did not terminate ah, hehe!!!");
}
}Operation Result:
Hello World!!!
Divisor is 0!
Divisor is zero after the program did not terminate ah, hehe!!! 4. Run-time error
The error class and its subclasses represent run-time errors, usually thrown by a Java virtual machine, with some wrong classes defined in the JDK, such as Virtualmachineerror
and OutOfMemoryError, the program itself cannot fix these errors. Generally do not extend the error class to create user-defined fault classes. While the RuntimeException class represents an error in the program code, it is extensible, and the user can create a specific runtime exception class.
The same thing about error (run-time errors) and run-time exceptions is that the Java compiler does not check them and will terminate when the program runs.
5, the best solution
for run-time exceptions, we do not use Try...catch to capture processing, but in the program development debugging phase, try to avoid this exception, once the exception is found, the correct practice will improve the design of the Code and Implementation methods, modify the program errors, so as to avoid this exception. Capturing and handling runtime exceptions is a good solution because you can avoid this kind of exception by improving your code implementation. for the check exception, didn't see?, honestly go according to the method of exception handling, either capture and solve with try...catch, or throw with throws!
For error (Run-time error), do not need to do any processing in the program, after the problem, should be in the outside of the program to find the problem, and then solve. vi. abnormal transformation and abnormal chainabnormal transformation has been mentioned above, in fact, after catching an exception, the exception is thrown with a new type of exception, this is generally for the exception of the information more intuitive! Like what:
Public Void Run () throws myexception{
...
try{
...
}catch (IOException e) {
...
throw new MyException ();
}finally{
...
}
}

Java 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.