Java's exception

Source: Internet
Author: User
Tags assert finally block instance method object object

Exception this thing, the program must have, although we are very reluctant to see it, but from another point of view, there are exceptions to the program has a problem, help us to correct in time. Sometimes there are many reasons for the program error, such as illegal input, type, null pointers and even insufficient memory, if the light from the software, we only know that it is a problem, it is not clear where the issue, to the software error is a very headache, because there may be too many problems, grammatical problem is better, After all, it can be seen visually that some of the logical problems are deadly, and we must start from the global perspective to find the root of the problem!

Transferred from: http://blog.csdn.net/zhangerqing

First, Introduction

Java provides us with a very perfect exception handling mechanism, so that we can focus more on the program, and sometimes encountered the need to add exception processing block, like eclipse will automatically prompt you, feel very happy! Let's look at some of the structural components of exception handling classes:

There are two main categories from the root: Error and exception. Error is a bug that the program cannot handle, such as OutOfMemoryError, Threaddeath, and so on. When these exceptions occur, the Java Virtual machine (JVM) typically chooses to terminate the thread. Exception is an exception that can be handled by the program itself, which is divided into two categories: Non-runtime exceptions (which occur at compile time, also known as checkexception) and runtime exceptions (which occur during a program run, also called uncheckexception). Non-runtime exceptions are generally referred to some code that does not adhere to the Java language specification, easy to see out, and easy to solve the exception, run-time exception is those in the process of running the exception, with uncertainty, such as null pointer exception, resulting in a lot of null pointers, so the run-time exception is uncertain, Often difficult to troubleshoot, there is a program in the logic errors, light from a piece of code to see the problem, need to look at the global to find errors, it will also cause the run-time exception, which requires us to write the program a lot of attention, as far as possible to deal with the exception, when the exception occurs, I hope that the program to the ideal

Ii. Types of exceptions

On the one hand, we can divide the anomaly into controlled exception and uncontrolled exception, in fact, the controlled exception is a non-runtime exception, the uncontrolled exception is run-time exception and error. On the other hand, we directly divide the exception into non-runtime exceptions and run-time exceptions.

Third, the process of exception handling

Use the try/catch/finally statement block to install the exception handler, where each try block contains statements that may have exceptions, and each catch block contains a program that handles the exception.

public class Test {public static void main (string[] args) {String filename = "D:\\test.txt"; try {filereader reader = new FileReader (filename); Scanner in = new Scanner (reader); String input = In.next (); int value = Integer.parseint (input); System.out.println (value);} catch (FileNotFoundException e) {e.printstacktrace ();} finally {System.out.println ("This is finally block!");}}}

  

If there is no test.txt in the D-Packing directory, the program throws an exception:

This is finally block!
Java.io.filenotfoundexception:d:\test.txt (the system cannot find the file specified.) )
At Java.io.FileInputStream.open (Native Method)
At Java.io.fileinputstream.<init> (fileinputstream.java:106)
At Java.io.fileinputstream.<init> (fileinputstream.java:66)
At Java.io.filereader.<init> (filereader.java:41)
At Test.main (test.java:10)

But the statement in the Finally block output, this aside, first remember, in the D disk under the new file Test.txt, and input content 2232, then to observe:

Output:

2322
This is finally block!

The statements in the finally block are still output, stating that the statements in the finally block are executed regardless of whether the program has any exceptions. Therefore, the finally block usually puts some statements to close the resource. Next we go on to do the experiment, we change the test.txt 2322 to ABC and see the result:

This is finally block!
Exception in thread "main" Java.lang.NumberFormatException:For input string: "ABC"
At Java.lang.NumberFormatException.forInputString (numberformatexception.java:48)
At Java.lang.Integer.parseInt (integer.java:447)
At Java.lang.Integer.parseInt (integer.java:497)
At Test.main (test.java:13)
Two points in the exception I have marked out, one is the red exception in thread "main", indicating where the exception was thrown, and the other is the Java.lang.NumberFormatException:For input string: " ABC ", indicating the type of exception, here we look at the previous result above, why did not throw the exception where the occurrence, carefully observe the source program, we found that the program we did not explicitly declare numberformatexception, And FileNotFoundException is our statement, here I summarize is said: 1, if I declare an exception in the program, then throw an exception, will not show the source, directly thrown. 2, if I do not declare in the program, then the program with the exception to throw the source. Why is this? Also, what will the system do when I don't explicitly declare it? This must be a certain regularity, and below we continue to do the experiment:

public class Test {public static void main (string[] args) {String filename = "d:\\test.txt";//Catch exception try {FileReader re Ader = new FileReader (filename); Scanner in = new Scanner (reader); String input = In.next (); int value = Integer.parseint (input); System.out.println (value);} catch (FileNotFoundException e) {//snap filenotfoundexceptione.printstacktrace ();} catch (NumberFormatException e) {//Nu Mberformatexceptione.printstacktrace (); Print exception information is the shape of: at Java.lang.NumberFor ... Information System.out.println ("I ' m here!");} finally {System.out.println ("This is finally block!");}}}

 

I've added a catch block, and I'm going to catch NumberFormatException, then the program outputs:

Java.lang.NumberFormatException:For input string: "ABC"
At Java.lang.NumberFormatException.forInputString (numberformatexception.java:48)
At Java.lang.Integer.parseInt (integer.java:447)
At Java.lang.Integer.parseInt (integer.java:497)
At Test.main (test.java:14)
I ' m here!
This is finally block!

There is no output exception thrown in place. Continue to change the code:

public class Test2 {public void open () {String filename = "D:\\test.txt"; try {filereader reader = new FileReader (filename); Scanner in = new Scanner (reader); String input = In.next (); int value = Integer.parseint (input); System.out.println (value);} catch (FileNotFoundException e) {e.printstacktrace (); System.out.println ("This is Test2 block!");} }}

  

public class Test3 {public void Carry () {Test2 t2 = new Test2 (); try {t2.open ();} catch (Exception e) {e.printstacktrace (); System.out.println ("This is Test3 block!");}}}

  

public class Test {public static void main (string[] args) {Test3 t3 = new Test3 (); T3.carry ();}}

  

The idea is: to handle the business in the Test2 class, the Test3 class calls the Open method of the Test2 class, and finally calls the carry method of the Test3 class in the test class, but I leave the exception in Test3 to see the result of the exception output:

Java.lang.NumberFormatException:For input string: "ABC"
At Java.lang.NumberFormatException.forInputString (numberformatexception.java:48)
At Java.lang.Integer.parseInt (integer.java:447)
At Java.lang.Integer.parseInt (integer.java:497)
At Test2.open (test2.java:13)
At Test3.carry (test3.java:6)
At Test.main (test.java:7)
This is Test3 block!

First, the exception thrown has no local information, and then output: This is Test3 block!, indicating that the exception is thrown from the carry method in the Test3 class, when we comment out the exception capture statement in the Test3 class, the exception is as follows:

Exception in thread "main" Java.lang.NumberFormatException:For input string: "ABC"
At Java.lang.NumberFormatException.forInputString (numberformatexception.java:48)
At Java.lang.Integer.parseInt (integer.java:447)
At Java.lang.Integer.parseInt (integer.java:497)
At Test2.open (test2.java:13)
At Test3.carry (test3.java:6)
At Test.main (test.java:7)

See here, I think the reader friends should have a certain feeling, said so much, is to explain a point, when the program can not handle the abnormal when it will do? This is true: if the current method declares the appropriate exception handler, such as if the above program has a catch (NumberFormatException e), it is thrown directly, but if there is no declaration, the caller will be found, and if the caller does not do the corresponding processing, it will always look forward , until the main method is found, and finally throws an exception, so the above phenomenon is not difficult to explain! Here we briefly summarize the process of exception handling: 1, in the possible error of the method plus Try/catch block statement, to invoke the exception handler. 2, when the exception occurs, jump directly to the corresponding exception handler catch, if any, throw an exception, execute the statement in the catch block, if not, find its caller until the main method. 3. If there is a finally block, the statement in the finally block is executed.

Attention:

1, a try can correspond to multiple catch. 2, there is a try must have at least one catch or finally (here by netizens actt001 correct, thank you!) )。 3, finally block is not necessary, optional. 4, in general, when an exception occurs, the statement in the catch block is executed, special case: When an exception is thrown in the main method, if the program declares the exception handler, the statement in the corresponding catch block is executed, if the program does not declare the appropriate exception handler, the statement in the catch block is not executed , throw an exception directly! So, where does this anomaly come from? Since there is a Try/catch statement in main (although not the corresponding exception handler), why is it not thrown, stating that the Try/catch block in the main method does not catch the exception at all, then what does the system do with it? In fact, in this case, the exception is directly dropped to the JVM, and the JVM is handled by: Directly Interrupt your program! It's that simple.

Iv. Common anomalies

nullpointerexception NULL pointer

Null pointer exception. This exception is thrown when an app tries to use null where the object is required. Example: Invoking an instance method of a null object, accessing the properties of a null object, calculating the length of a null object, throwing null with a throw statement, and so on

ClassNotFoundException cannot find a class

The class exception could not be found. This exception is thrown when an application attempts to construct a class based on a class name in string form, and when a class file of the corresponding name is not found after traversing Classpah.

classcastexception Type conversions

arithmeticexception Arithmetic conditions

Arithmetic condition exception. For example: integers except 0.

arrayindexoutofboundsexception array out of bounds

Array index out-of-bounds exception. Thrown when the index value of an array is negative or greater than or equal to the size of the arrays.

V. Exceptions and Errors

Exception: In Java, the error of the program is mainly syntax errors and semantic errors, a program in the compile and run the error we call an exception, it is the JVM (Java Virtual machine) notify you a way, in this way, the JVM let you know that you have made a mistake, Now there is a chance to modify it. Exception classes are used in Java to represent exceptions, and different exception classes represent different exceptions. But all exceptions in Java have a base class, called exception.

Error: It refers to a reasonable application that cannot intercept a serious problem, most of which is an anomaly, and the error is a failure of the JVM (although it can be any system-level service). Therefore, errors are difficult to handle, and generally developers cannot handle these errors, such as memory overflows.

Vi. assert (Assert)

Assert is a new feature that jdk1.4 only starts to support, primarily during development and testing, to ensure performance, which is usually closed after the program is officially released. It is easy to enable assertions, set-ea or-enableassertions in the startup parameters.

There are two cases of an assert expression:

1) Assert exp1 at this point the EXP1 is a Boolean type of expression

When its value is true, it runs through, and if False, a corresponding Assertionerror is thrown, noting that it can be caught.

2) Assert exp1:exp2 at this time exp1, and EXP2 can be a primitive type or an Object object, when the value of EXP1 is true, and EXP2 is not evaluated, and when the value of EXP1 is false, The Assertionerror will be thrown, and the result of the EXP2 will be used as a parameter in the Assertionerror constructor, and the GetMessage () method can be used to print the result of the EXP2 when using catch that error.

The use of assertions should be noted: assertions are just tools used to debug the program, not as part of the program, or someone using assertions instead of Try/catch, which is wrong, 1, this is contrary to the assertion, 2, the assertion will be closed after the program is published, if it is part of the program, Then when the assertion is closed, the program inevitably goes wrong. 3, there are better ways, such as Try/catch, why also use assertions. Therefore, it is better not to say that the assertion as part of the program, from the heart you can think of it as dispensable on the line.

VII. FAQ 1, finally, and return questions

We usually say: Finally in the content of whether the program is not abnormal, will be executed, then if our program in the try and catch block return, finally will also execute? The reader can guess first, analyze it, and then we'll do the experiment:

public class Finallytest {public static void main (string[] args) {Boolean file = open (); System.out.println ("This is main return value:" + file);} public static Boolean open () {String filename = "D:\\TEST.TXTP"; try {filereader reader = new FileReader (filename); Scanner in = new Scanner (reader); String input = In.next (); int value = Integer.parseint (input); System.out.println (value); return true; } catch (FileNotFoundException e) {System.out.println ("This is catch_for_filenot ... block!"); return false;} finally {System.out.println ("This is finally block!");}}}

  

Deliberately write the filename wrong, create an exception, the output is the following:

This is catch_for_filenot ... block!
This is finally block!
This is main return value:false

From here, the program outputs the catch block and then executes the finally block, although it has been returned in the catch, the last execution of the Mian method, and the output is false, indicating that the catch block also returned successfully. Therefore, in the face of doubt, we can be very sure to answer, even if there is a return statement, finally block will certainly be executed!

2, try not to use catch and finally together

As I have shown above in the demo program, Try/catch/finally, as mentioned in the book Big Java, is not recommended because it affects the readability of the program, the best way to do this is to use try/catch nesting, catch to catch exceptions, Finally, to close the resource, modify the following:

public class Finallytest {public static void main (string[] args) {Boolean file = open (); System.out.println ("This is main return value:" + file);} public static Boolean open () {String filename = "D:\\TEST.TXTP"; try {try {filereader reader = new FileReader (filename); Scanner in = new Scanner (reader); String input = In.next (); int value = Integer.parseint (input); System.out.println (value); return true; } finally {//some operations that close the resource System.out.println ("This is finally block!");}} catch (FileNotFoundException e) {System.out.println ("This is catch_for_filenot ... block!"); return false;}}}

  

3. Custom Exceptions

After all, the system comes with the exception processor does not meet all the requirements, because for our developers, the more detailed the exception thrown, the easier we find the problem, not all the problems are thrown exception it? It's too general. In the actual development, we can make the custom exception processor according to our own needs.

/** * Custom Exception handlers, inheriting exception or runtimeexception, depending on the situation. * @author erqing * */public class Namenotsupportexception extends RuntimeException {private static final long Serialversi Onuid = 7295869280641332966L; Public namenotsupportexception () {} public namenotsupportexception (String message) {super (message);}}

  

public class Definetest {public static void main (string[] args) {String name = "Egg"; Erqing ". Equals (name)) {throw new Namenotsupportexception (" erqing ");} Else{system.out.println ("name is ok!");}}}

  

Exception in thread "main" Namenotsupportexception:erqingat Definetest.main (Definetest.java:7)

  

Java's exception

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.