Java beauty [from cainiao to masters] Exception

Source: Internet
Author: User
Tags 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 chapter describes the exceptions in the Java [from cainiao to masters] series. Through this chapter, we can thoroughly understand the Exception Handling Mechanism in Java.

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

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 );
Bytes in = new bytes (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, indicating that the statements in the finally block are executed no matter whether the program is abnormal or not. 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, it is directly thrown without explicit source. 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:

[Java]
Public class Test {
 
Public static void main (String [] args ){
 
String filename = "d :\\ test.txt ";
 
// Capture exceptions
Try {
FileReader reader = new FileReader (filename );
Bytes in = new bytes (reader );
String input = in. next ();
Int value = Integer. parseInt (input );
System. out. println (value );
} Catch (FileNotFoundException e) {// capture FileNotFoundException
E. printStackTrace ();
} Catch (NumberFormatException e) {// NumberFormatException
E. 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:

[Java]
Public class Test2 {

Public void open (){
String filename = "d :\\ test.txt ";
Try {
FileReader reader = new FileReader (filename );
Bytes in = new bytes (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! ");
}
}
}
[Java]
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! ");
}
}
}
[Java]
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 no exception exists, 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. A try must have at least one catch. 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

NullPointerException NULL 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.

ClassNotFoundException class 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.

ClassCastException type conversion

ArithmeticException arithmetic Condition

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

ArrayIndexOutOfBoundsException array 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.

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:

[Java]
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 {
FileReader reader = new FileReader (filename );
Bytes in = new bytes (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:

[Java]
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 );
Bytes in = new bytes (reader );
String input = in. next ();
Int value = Integer. parseInt (input );
System. out. println (value );
Return true;
 
} Finally {
// Some operations to disable Resources
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.

[Java]
/**
* The custom Exception processor inherits Exception or RuntimeException, depending on the situation.
* @ Author erqing
*
*/Www.2cto.com
Public class NameNotSupportException extends RuntimeException {
 
Private static final long serialVersionUID = 7295869280641332966L;
 
Public NameNotSupportException (){
}
 
Public NameNotSupportException (String message ){
Super (message );
}
}
[Java]
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! ");
}
}
}
[Java]
Exception in thread "main" NameNotSupportException: erqing
At DefineTest. main (DefineTest. java: 7)

 

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.