An in-depth discussion of exceptions and error handling in Java _java

Source: Internet
Author: User
Tags error handling instance method readfile throw exception throwable
Exceptions and Errors:
Abnormal:


In Java, program errors are mainly syntax errors and semantic errors, the error that occurs when a program compiles and runs we call it an exception, and it's a way for the VM to notify you that in this way, the VM lets you know that you (the developer) have made a mistake and now has a chance to modify it. Exception classes are used in Java to represent exceptions, and different exception classes represent different exceptions. But in Java, all exceptions have a base class called exception.


Error:


It refers to a serious problem that a reasonable application cannot intercept. Most of them are anomalies. An error is a failure of the VM (although it can be any system-level service). Therefore, errors are difficult to handle, and the average developer (not you, of course) cannot handle these errors, such as a memory overflow. As with exceptions, error classes are used in Java to represent errors, and different error classes represent different errors. But in Java, all errors have a base class called error.


In summary, we can know that the most essential difference between the exception and the error is that the exception can be handled by the developer and error when the system was originally brought, generally unable to deal with and do not need our programmers to deal with.


1. An exception is an event that occurs during the execution of a program that interrupts the operation of normal instructions.


2. Error, an action or instance that deviates from acceptable code behavior


Structure Classification of exceptions:


1. Run-time Exceptions (no exceptions checked)


2. Compile-time exceptions (checked for exceptions)


The run exception is runtimeexception; all the rest is a compilation exception


There is a common parent class throwable in Java for exception exception and error errors.


Error Exception


RuntimeException several subclasses


1, Java.lang.ArrayIndexOutOfBoundsException


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


2, Java.lang.ArithmeticException


Arithmetic condition exception. For example: integers except 0.


3, Java.lang.NullPointerException


Null pointer exception. The exception is thrown when an application attempts to use null where the object is required. For example, invoking an instance method of a null object, accessing a null object's


property, compute the length of the null object, throw NULL using the throw statement, and so on


4, Java.lang.ClassNotFoundException


The class exception was not found. When an application attempts to construct a class based on a class name in the form of a string, and when the class file of the corresponding name is not found after traversing the classpah, throw


The exception.


Handling of Exceptions:


try{}catch{}


try{}catch{}finally{} no exception finally code block will be executed


try{}finally{} can also be used in combination, but catch{}finally{} cannot be


Note: In an inheritance relationship, a subclass overrides a method of the parent class, and the scope of the throw exception cannot be broader than the parent class


Use of exceptions


In the use of the exception is mainly the demo code, we usually write code in the process will encounter (of course, only a small part), a little bit of it!


Example 1. This example mainly uses two methods to demonstrate the execution flow of the code after the exception.


Copy Code code as follows:

public static void TestException1 () {
int[] ints = new int[] {1, 2, 3, 4};
System.out.println ("Before abnormal appearance");
try {
System.out.println (Ints[4]);
System.out.println ("I also have the honor to execute to");//After an exception occurs, the following code cannot be executed
catch (Indexoutofboundsexception e) {
SYSTEM.OUT.PRINTLN ("Array Out of bounds error");
}
System.out.println ("After abnormal appearance");
}



/*output:


Before an exception occurs


Array out of bounds error


Often appear after


*/


Copy Code code as follows:

public static void TestException2 () {
int[] ints = new int[] {1, 2, 3, 4};
System.out.println ("Before abnormal appearance");
System.out.println (Ints[4]);
System.out.println ("I was fortunate enough to do it")//After the exception, the code behind him could not be executed
}



First of all, point out the deficiencies in the example, Indexoutofboundsexception is a non-inspected exception, so do not try...catch ... Show capture, but my goal is to treat the same exception in a different way, to see what will be different and the result (this is the only way to do it). When an exception occurs, the first method simply jumps out of the try block, but the code behind it executes as well. But the second one is different. Jump straight out of the way, more tough. From the first method we see that try...catch ... is a "transactional" safeguard that is designed to ensure that a program runs in an unusual situation, and it also tells the programmer about the details of the error in the program (this detail is sometimes dependent on programmer design).


Example 2. Throwing Exceptions again


Copy Code code as follows:

public class Rethrow {
public static void ReadFile (String file) throws FileNotFoundException {
try {
Bufferedinputstream in = new Bufferedinputstream (new FileInputStream (file));
catch (FileNotFoundException e) {
E.printstacktrace ();
System.err.println ("Do not know how to handle the exception or do not want to deal with it, but do not deal with the inappropriate, which is to throw the exception to the previous level of processing");
Throwing Exceptions again
Throw e;
}
}
public static void Printfile (String file) {
try {
ReadFile (file);
catch (FileNotFoundException e) {
E.printstacktrace ();
}
}
public static void Main (string[] args) {
Printfile ("D:/file");
}
}



The original intention is good, let's try to fix the program, but in reality we have very little chance of fixing it, and we use it often to record the wrong information. If you are tired of dealing with exceptions, it may be a good relief for you to throw out the exception again. Leave the exception to the previous level, throw it to the person who called it, and let him think. In this case, the Java exception, of course, refers to an exception, which adds a lot of trouble to us, even though its starting point is good.


Example 3. Use of abnormal chain and abnormal loss


Copy Code code as follows:

Exceptiona,exceptionb,exceptionc
public class Exceptiona extends Exception {
Public Exceptiona (String str) {
Super ();
}
}
public class Exceptionb extends Exceptiona {
Public exceptionb (String str) {
Super (STR);
}
}
public class Exceptionc extends Exceptiona {
Public Exceptionc (String str) {
Super (STR);
}
}



Exceptions lost:


Copy Code code as follows:

public class Nevercaught {
static void F () throws exceptionb{
throw new Exceptionb ("Exception B");
}
static void G () throws Exceptionc {
try {
f ();
catch (Exceptionb e) {
Exceptionc C = new Exceptionc ("Exception a");
Throw C;
}
}
public static void Main (string[] args) {
try {
g ();
catch (Exceptionc e) {
E.printstacktrace ();
}
}
}
/*
exception. Exceptionc
At exception. NEVERCAUGHT.G (Nevercaught.java:12)
At exception. Nevercaught.main (nevercaught.java:19)
*/



Why just print out the exceptionc and not print out the exceptionb? This is to analyze it yourself!


The above situation is equivalent to the lack of an exception, which is very bad in the process of our mistakes. So what do we do when we get to the top? This is where the exception chain comes in: Save the exception information and do not lose the original exception while throwing another exception.


Copy Code code as follows:

public class Nevercaught {
static void F () throws exceptionb{
throw new Exceptionb ("Exception B");
}
static void G () throws Exceptionc {
try {
f ();
catch (Exceptionb e) {
Exceptionc C = new Exceptionc ("Exception a");
Abnormal company
C.initcause (e);
Throw C;
}
}
public static void Main (string[] args) {
try {
g ();
catch (Exceptionc e) {
E.printstacktrace ();
}
}
}
/*
exception. Exceptionc
At exception. NEVERCAUGHT.G (Nevercaught.java:12)
At exception. Nevercaught.main (nevercaught.java:21)
Caused by:exception. Exceptionb
At exception. NEVERCAUGHT.F (Nevercaught.java:5)
At exception. NEVERCAUGHT.G (NEVERCAUGHT.JAVA:10)
... 1 more
*/



The nature of this anomaly chain is that all exceptions are available because the Initcause () method inherits from Throwable.


Example 4. clean-up work


Cleanup is essential to us, because if there are some resource-consuming operations, such as IO,JDBC. If we run out of time and do not properly shut down in a timely manner, the consequences will be serious, which means memory leaks. The presence of anomalies requires that we design a mechanism in which resources can be cleaned up in a timely manner, regardless of the circumstances. This is finally.


Copy Code code as follows:

public void ReadFile (String file) {
BufferedReader reader = null;
try {
reader = new BufferedReader (New InputStreamReader (
New FileInputStream (file));
Do some other work
catch (FileNotFoundException e) {
E.printstacktrace ();
finally {
try {
Reader.close ();
catch (IOException e) {
E.printstacktrace ();
}
}
}



The example is very simple and is an example of reading a file. Such examples are also very common in JDBC operations. (So, I think the timely and correct cleaning of resources is one of the basic qualities of a programmer.) )


Try...finally structure is also a means to ensure the proper shutdown of resources. If you're not sure what's going to happen during code execution that can cause resources to not be cleaned up, you wrap the "suspicious" code in a try and then clean up the resource in finally. Give an example:


Copy Code code as follows:

public void ReadFile () {
BufferedReader reader = null;
try {
reader = new BufferedReader (New InputStreamReader (
New FileInputStream ("file"));
Do some other work
Close Reader
Reader.close ();
catch (FileNotFoundException e) {
E.printstacktrace ();
catch (IOException e) {
E.printstacktrace ();
}
}



Let's pay attention to the difference between this method and the previous one, the next person may get used to a little bit better and close reader early. But often counterproductive, because the reader.close () before the exception can occur at any time, such a code structure can not prevent any abnormal appearance. Because the program will jump out of the place where the anomaly appears, the following code cannot be executed (this should be proved on the above example). Then we can use try...finally to transform:


Copy Code code as follows:

public void ReadFile () {
BufferedReader reader = null;
try {
try {
reader = new BufferedReader (New InputStreamReader (
New FileInputStream ("file"));
Do some other work
Close Reader
finally {
Reader.close ();
}
catch (FileNotFoundException e) {
E.printstacktrace ();
catch (IOException e) {
E.printstacktrace ();
}
}



Early shutdown of resources is a good behavior, because the longer you forget the greater the likelihood of closing. In this way in conjunction with the try...finally guarantee foolproof (don't bother, Java is so modest).


Again, if I want to open a file in the constructor or create a JDBC connection, because we want to use this resource in other methods, we cannot close the resource early in the constructor. So we don't have a thing? The answer is No. Take a look at the following example:


Copy Code code as follows:

public class Resourceinconstructor {
BufferedReader reader = null;
Public Resourceinconstructor () {
try {
reader = new BufferedReader (New InputStreamReader FileInputStream (""));
catch (FileNotFoundException e) {
E.printstacktrace ();
}
}
public void ReadFile () {
try {
while (Reader.readline ()!=null) {
Do some work
}
catch (IOException e) {
E.printstacktrace ();
}
}
public void Dispose () {
try {
Reader.close ();
catch (IOException e) {
E.printstacktrace ();
}
}
}



This part is a bit more, but the anomaly is really easy to use the things that are difficult, Java still have a lot of things to dig deep
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.