Java Exception Handling and exception Mechanism

Source: Internet
Author: User
Tags finally block

(1) What is an exception?
When there is an external environment problem that cannot be controlled by the program (the file provided by the user does not exist, the file content is damaged, and the network is unavailable...), Java will describe it with an exception object.
Java uses two methods to handle exceptions:
1. handle exceptions directly;
2. Send the exception to the caller for processing.

Java exceptions can be divided into three types:
A. Check exception: Java. Lang. Exception. Check exception ------ the program is correct, but the external environment conditions are not met. For example: user errors and I/O problems-the Program tries to open a remote socket port that does not exist. This is not a logic error of the program itself, but probably a remote machine name error (User spelling error ). The Java compiler enforces the processing of such exceptions. If such exceptions are not caught, the program cannot be compiled.
B. runtime exception: Java. lang. runtimeexception. runtime exception ------ this means that the program has bugs, such as array out-of-bounds, 0 is excluded, and the input parameter does not meet the specifications ..... this type of exception must be avoided by changing the program. The Java compiler requires that such exceptions be handled.

C. Error: Java. Lang. Error. Error ------ is common and difficult to solve through a program. It may be due to program bugs, but it is generally due to environmental problems, such as memory depletion. Errors do not need to be handled in the program, but are handled in the runtime environment.

The top layer is the java. Lang. throwable class. Check exceptions, runtime exceptions, and errors are all child classes of this class. Java. Lang. Exception and Java. Lang. error are inherited from Java. Lang. throwable, while Java. Lang. runtimeexception is inherited from Java. Lang. Exception.

(2) how to handle exceptions?
A, try... catch. When an exception occurs during the running of the program, the program will be interrupted from the occurrence of the exception and the exception information will be thrown out.

Note: Both arithmeticexception and arrayindexoutofboundsexception are runtime exceptions (Java. lang. runtimeexception), if you do not need try... catch capture, the program can also be compiled; but if it is a checking exception (Java. lang. exception), and must use try... catch... you can compile the SDK only after processing it.

Int x = (INT) (math. random () * 5); int y = (INT) (math. random () * 10); int [] Z = new int [5]; try {system. out. println ("Y/x =" + (y/X); system. out. println ("Y =" + Y + "Z [y] =" + Z [y]);} catch (arithmeticexception exc1) {system. out. println ("Arithmetic Operation exception:" + exc1.getmessage ();} catch (arrayindexoutofboundsexception exc2) {system. out. println ("data out-of-bounds exception:" + exc2.getmessage ());}

B, finally. If you set the Finally block to try... catch... after a statement, the Finally block is generally executed. It is equivalent to 10 thousand of the Security. Even if the previous try block has an exception and there is no catch block corresponding to the exception, the Finally block will be executed immediately.
In the following cases, finally blocks will not be executed:
(1) An exception occurred in the Finally block;
(2) The thread where the program is located is killed;
(3) system. Exit () is used in the previous Code ();
(4) disable the CPU.

C. Throw an exception, that is, the use of throws.

Package draw; import Java. util. extends; public class sub {public static void main (string [] AGRs) {try {divide (); // 2. we call the method that throws an exception below in the mian method. In this case, we use the try-catch statement to handle it.} catch (exception e) {system. out. println ("the divisor cannot be zero"); E. printstacktrace (); // 3. this method prints the exception information} public static void divide () throws exception {// 1. here we throw an exception and declare it as static to call it without creating an object. Wrote input = new partition (system. in); system. out. println ("Enter dividend:"); int num = input. nextint (); system. out. println ("Enter the divisor:"); int num2 = input. nextint (); system. out. println ("the quotient of num divided by num2 is:" + num/num2 );}}

The above is a general process of throwing an exception-capturing an exception when calling a method. If we do not want to use try-catch to catch exceptions when calling a method in the preceding example, we can call its main method to throw the exception again. The new code example is as follows:

Package draw; import Java. util. failed; public class sub {public static void main (string [] AGRs) throws exception {// here we throw the exception again. In this example, we handed it over to the Java Virtual Machine for processing, if it is a common method, there are two options: one is to throw again, the other is to try-catch for processing, and the exception must be finally thrown. Normally, we do not write like an example. When we encounter the main method, we use try-catch to process divide ();} public static void divide () throws exception {writable input = new writable (system. in); system. out. println ("Enter dividend:"); int num = input. nextint (); system. out. println ("Enter the divisor:"); int num2 = input. nextint (); system. out. println ("the quotient of num divided by num2 is:" + num/num2 );}}

Exception is the parent class of all caught exception classes. I don't want to capture any other exceptions under it during the capture. What should we do if we only want to capture one or more exceptions? See the writing method:

Public static void divide () throws arithmeticexception, inputmismatchexception {code block} are separated by commas. You can use the thows keyword to specify multiple thrown exceptions.
(3) handling rules for multiple exceptions:
Define multiple catch to precisely locate exceptions. If a special catch block is defined for a subclass exception, and the exception of the parent class is placed in another Catch Block, the following rules must be met: the processing block of the subclass exception must be before the parent exception processing block; otherwise, a compilation error occurs. Therefore, the more special exceptions are processed, the more common the exceptions are processed later. This is similar to the order of firewall rules: more special rules come first, and more common rules are later.
You can also define and throw an exception by following two steps: create an exception and throw an exception (instantiate an exception object and then throw it with thow ). When an exception is created, the row information at the exception creation is contained. When an exception is caught, the stack trace can be used). If the same line of code is created and an exception is thrown, it is very useful for program debugging. Therefore, thow new XXX () has become a standard exception throw paradigm.
For Exception Handling, there is a valid default rule: Throw Up ----- The called class does not handle any exceptions encountered during the running process, but directly throws up, to the upper-level calling class, the calling class processes the exception according to the application system requirements and specific exception handling rules. For example, it outputs the exception stack information to the console and prints it in the log file. In an image, it means who uses it and who processes it (the upper-layer call class.

Http://edu.codepub.com/2009/0806/12426.php ()

Http://blog.sina.com.cn/s/blog_752265d10100wl8u.html ()

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.