Java beauty [from cainiao to masters] exception

Source: Internet
Author: User
Tags finally block integer division

Exception, which must be included in the program. Although we are not happy to see it, from another perspective, exceptions indicate that the program has problems and help us to correct them in time. Sometimes there are many causes of program errors, such as invalid input, type, null pointer, or even insufficient memory. From the software perspective, we only know that the program has a problem, it is not clear where the problem is. troubleshooting software errors is a headache, because there may be too many problems, and the syntax problem is better. After all, it can be seen visually, some logical problems are fatal. We must start from the global perspective to find the root cause of the problem! Based on this, we need to use the exception mechanism. I remember when I first learned to write a program, the teacher always said that there may be errors. Don't forget to add the exception handling block. At that time, I thought that since it was something I wrote, don't you know if there will be any errors? At that time, this problem plagued me for a period of time, but I don't know how simple the program is. Later I wrote more clearly. Exceptions are very important! This chapterThe beauty of Java [from cainiao to masters] SeriesException. Through this chapter, we can have a deep understanding of the Exception Handling Mechanism in Java.

If you have any questions during reading, please contact egg in time.

Mailbox: xtfggef@gmail.com Weibo: http://weibo.com/xtfggef

If there is reprint, please explain the source: http://blog.csdn.net/zhangerqing

I. Introduction

Java provides us with a perfect exception handling mechanism, so that we can concentrate more on writing programs. Sometimes, when you need to add Exception Handling blocks, eclipse will automatically prompt you, I feel very happy! Let's take a look at the structure of some classes for exception handling:

There are two main categories starting from the root: Error and exception. Error is an error that cannot be processed by the program, such as outofmemoryerror and threaddeath. When these exceptions occur, the Java Virtual Machine (JVM) generally chooses to terminate the thread. Exception is an exception that can be handled by the program itself. This exception is divided into two categories: Non-runtime exception (occurs in the compilation stage, also known as checkexception) and runtime exception (occurs during the program running, it is also called uncheckexception ). Non-runtime exceptions generally refer to some codes that do not comply with the Java language specifications and are easy to see and solve. runtime exceptions are exceptions generated during the program running, there are many causes of uncertainty, such as null pointer exceptions. Therefore, runtime exceptions are uncertain and often difficult to troubleshoot. There are also logical errors in the program, errors that can only be detected globally from a piece of code may cause runtime exceptions. This requires us to pay more attention when writing programs and try to handle exceptions as much as possible, when an exception occurs, we hope the program can run in the ideal way!

Ii. Exception type

On the one hand, we can divide exceptions into controlled exceptions and uncontrolled exceptions. Generally, controlled exceptions are non-runtime exceptions, and uncontrolled exceptions are runtime exceptions and errors. On the other hand, exceptions are classified into non-runtime exceptions and runtime exceptions.

III,Exception Handling Process

Use the try/catch/finally statement block to install the exception handling program. Each try block contains statements that may cause exceptions, and each catch block contains programs that handle exceptions,

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 test.txt is not found in the ddisk root directory, the program throws an exception:

This is finally block!
Java. Io. filenotfoundexception: D: \ test.txt (the specified file cannot be found .)
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)

However, the finallyblock's sentence is output. For the moment, I will not talk about it. I will first remember to create a new file test.txt on the d Drive and enter the content 2232. Then I will observe it:

Output:

2322
This is finally block!

The statements in the Finally block are still output. Description:The statements in the Finally block are executed no matter the program has any exceptions.. Therefore, the Finally block usually contains some statements to close the resource. Next we will continue the experiment. We will change 2322 in test.txt to ABC to 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)
I have marked the two points in this exception. One is the red exception in thread "main", indicating the place where the exception is thrown, and the other is Java. lang. numberformatexception: for input string: "ABC" indicates the type of the exception. Here, let's take a look at the previous result. Why didn't the exception be thrown? look carefully at the source program. We found that, in the program, we did not explicitly declare numberformatexception, and filenotfoundexception was declared. Here I will summarize: 1. If I declare an exception in the program, when an exception is thrown, the source is not displayed and thrown directly. 2. If I do not declare it in the program, the program will throw the exception source at the same time. Why? What else will the system do when I do not explicitly declare it? There must be a certain rule. Next we will continue to do the experiment:

Public class test {public static void main (string [] ARGs) {string filename = "D: \ test.txt "; // catch exceptions. Try {filereader reader = new filereader (filename); identifier in = new identifier (Reader); string input = in. next (); int value = integer. parseint (input); system. out. println (value);} catch (filenotfoundexception e) {// capture filenotfoundexceptione. printstacktrace ();} catch (numberformatexception e) {// numberfor Matexceptione. printstacktrace (); // print the exception information, for example, at java. Lang. numberfor.... system. Out. println ("I'm here! ");} Finally {system. Out. println (" this is finally block! ");}}}

I added a Catch Block to catch numberformatexception, then the program 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 test. Main (test. Java: 14)
I'm here!
This is finally block!

No output exception is thrown. Continue code modification:

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 process the business in Test2, test3 calls the open method of Test2, and finally calls the carry method of test3 in the test class. However, I leave the exception in test3, check the output result of the exception:

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 thrown exception has no information, and the output is: This is test3 block !, This exception is thrown from the carry method in test3. When we comment out the exception capture statement in test3, 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)

Here, I think readers should have some feelings. After talking so much, I just want to explain what will happen when the program cannot handle exceptions? Yes: if the current method declares the corresponding exception processor, if the above program adds catch (numberformatexception E), it will be thrown directly, but if there is no declaration, the caller will be found. If the caller does not perform the corresponding processing, the caller will continue to look forward until the main method is found and an exception is thrown, so the above phenomenon is not difficult to explain! Here we will briefly summarize the exception handling process: 1. Add a try/Catch Block statement to the methods that may encounter errors to call the exception processor. 2. When an exception occurs, directly jump to the exception processor catch. If any, throw an exception and execute the statement in the Catch Block. If not, find its caller, until the main method. 3. If a Finally block exists, execute the statement in the Finally block.

Note:

1. A try can correspond to multiple catch entries. 2. If there is a try, at least one catch or finally is required.Actt001Correct, thank you !). 3. Finally blocks are not mandatory and optional. 4. Generally, when an exception occurs, the catch BLOCK statement is executed. In special cases, if the program declares the exception processor when an exception is thrown in the main method, execute the statements in the corresponding catch block. If the program does not declare the corresponding exception processor, it will not execute the statements in the Catch Block and directly throw an exception! So where does this exception come from? Since there is a try/catch statement in main (although it is not the corresponding exception processor), why not throw it, it means that the try/catch root in the main method has not caught the exception. How can this problem be solved? In fact, in this case, exceptions are directly thrown to the JVM, And the JVM's processing method is: directly interrupt your program! That's simple.

IV,Common exceptions

NullpointerexceptionNull Pointer

Null Pointer exception. This exception is thrown when the application tries to use null where the object is required. For example, call the instance method of the null object, access the attribute of the null object, calculate the length of the null object, and throw null using the throw statement.

ClassnotfoundexceptionClass not found

Class exception not found. This exception is thrown when the application tries to construct a class based on the class name in the string format and cannot find the class file with the corresponding name after traversing the classpah.

ClasscastexceptionType conversion

ArithmeticexceptionArithmetic Condition

Arithmetic condition exception. For example, integer division by zero.

ArrayindexoutofboundsexceptionArray out-of-bounds

An error occurred while exiting the array index. If the index value of the array is negative or greater than or equal to the size of the array, throw.

 

This content will be updated constantly. Readers and friends are invited to constantly raise their own meaningful exceptions while reading this article, and enrich their blog posts. You are welcome to actively supplement this article!

If you have any questions, contact egg.

Mailbox: xtfggef@gmail.com Weibo:Http://weibo.com/xtfggef

5. Exceptions and errors

Exception: in Java, program errors are mainly syntax errors and semantic errors. errors that occur during compilation and runtime of a program are called exceptions. They are JVM (Java Virtual Machine) one way to notify you, through which JVM lets you know that you have made a mistake and now you have a chance to modify it. In Java, exception classes are used to indicate exceptions. Different exception classes represent different exceptions. However, all exceptions in Java have a base class called exception.

Error: it refers to a serious problem that a reasonable application cannot intercept, most of which are abnormal, an error is a failure of JVM (although it can be a service of any system level ). Therefore, errors are hard to handle. Generally, developers cannot handle these errors, such as memory overflow.

6. Assert)

Assert is a new feature that jdk1.4 supports. It is mainly enabled during development and testing. To ensure performance, it is usually disabled after the program is officially released. It is easy to enable assertions. Set-ea or-enableassertions in the startup parameters.

The assert expression has two conditions:

1) assert exp1 the exp1 is a Boolean expression at this time.

When its value is true, the Operation passes. If it is false, a corresponding assertionerror is thrown. Note that it can be caught.

2) assert exp1: exp2 exp1 is the same as exp1 at this time, and exp2 can be of the basic type or an object. If the value of exp1 is true, the same as exp2 is not computed; when the value of exp1 is false, assertionerror is thrown, and the result of exp2 is used as a parameter in the assertionerror constructor. When the error is caught, getmessage () can be used () method to print the exp2 result.

When using assertions, it should be noted that assertions are only a tool used to debug the program. They should not be part of the program, or some may use assertions to replace try/catch, 1. This is contrary to the assertion. 2. The assertion will be closed after the program is released. If it is used as part of the program, when the assertion is closed, program problems are inevitable. 3. There are better methods, such as try/catch. Why are assertions used. Therefore, it is better not to say that assertions are part of the program. In your mind, you can regard them as dispensable.

VII. FAQs

1. Finally and return problems

We usually say that the finally content will be executed no matter whether the program is abnormal or not. If our program returns in the try and catch blocks, will the finally content be executed? Readers can guess, analyze, and then perform 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!");}}}

Intentionally write an error in filename and create an exception. The output is as follows:

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

It can be seen from this that the program first outputs the Catch Block and then executes the Finally block. Although it has already returned the catch, it finally executes the mian method and outputs false, it indicates that the catch block is successfully returned. Therefore, in the face of questions, we can answer with certainty that even if there is a return statement, the Finally block will be executed!

2. Try not to use catch and finally together.

Like the demo program above, try/catch/finally are used together. As mentioned in big Java, we do not recommend this because it will affect the readability of the program, the best practice is to use try/catch nesting, catch to catch exceptions, and finally to close resources. The modification is as follows:

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.txt P "; try {try {filereader reader = new filereader (filename); plaintext in = new plaintext (Reader); string input = in. next (); int value = integer. parseint (input); system. out. println (value); Return true;} fin Ally {// some resource close operations 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 exception processor provided by the system cannot meet all requirements, because for our developers, the more detailed the exception thrown, the easier it is to find the problem, cannot all problems throw an exception? Too general. In actual development, we can customize the exception processor as needed.

/*** Custom exception processor, inheriting exception or runtimeexception, depending on the situation. * @ author erqing **/public class namenotsupportexception extends runtimeexception {Private Static final long serialversionuid = signature; Public namenotsupportexception () {} public namenotsupportexception (string message) {super (Message );}}
public class DefineTest {public static void main(String[] args) {String name = "egg";if(!"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)

 

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.