Exception and error handling in JAVA

Source: Internet
Author: User
Tags constructor error handling exception handling instance method integer division readfile string format throwable

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 collectively referred to as exceptions. They are VM (Virtual Machine) errors) one way to notify you, through which VM lets you know that you (developers) have made an error and now 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 them are abnormal. An error is a fault of the VM (although it can be a service of any system level ). Therefore, errors are hard to handle. Generally, developers (not you) cannot handle these errors, such as memory overflow. Similar to exceptions, errors are represented by error classes in Java. Different error classes indicate different errors. However, all errors in Java have a base class called Error.
To sum up, we can know that the most essential difference between exceptions and errors is that exceptions can be handled by developers. When errors occur, the system comes with them. Generally, they cannot be handled and do not need to be handled by our programmers.


1. An exception is an event that occurs during the execution of a program. It interrupts the running of normal commands.
2. Error. An action or instance that deviates from an acceptable code behavior

Exception Structure classification:

1. Runtime exception (No exception is checked)

2. Exceptions during compilation (checked exceptions)

Running exceptions are RuntimeException; all others are compilation exceptions.

Exception and Error in Java have a common parent class Throwable.

Error Exception

RuntimeException subclasses

1. java. lang. ArrayIndexOutOfBoundsException
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.
2. java. lang. ArithmeticException
Arithmetic condition exception. For example, integer division by zero.
3. java. lang. NullPointerException
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 and access

Attribute, calculate the length of the null object, and throw null using the throw statement.
4. java. lang. ClassNotFoundException
Class exception not found. When the application tries to construct a class based on the class name in the string format, but cannot find the class file with the corresponding name after traversing the CLASSPAH

This exception occurs.

Exception handling:

Try {} catch {}
Try {} catch {} finally {} will be executed no matter whether the finally code block is abnormal or not.
Try {} finally {} can also be used in combination, but catch {} finally {} cannot

Note: in the inheritance relationship, the subclass overwrites the method of the parent class, and the range of thrown exceptions cannot be wider than that of the parent class.

 

Abnormal Use

When exceptions are used, this part mainly demonstrates the code. This is what we usually encounter when writing code (of course, it is only a small part!

 

Example 1: This example compares two methods to demonstrate the code execution process after an exception occurs.

The code is as follows: Copy code


Public static void testException1 (){

Int [] ints = new int [] {1, 2, 3, 4 };

System. out. println ("before an exception occurs ");

Try {

System. out. println (ints [4]);

System. out. println ("Do I still have the honor to execute it?"); // after an exception occurs, subsequent code cannot be executed.

} Catch (IndexOutOfBoundsException e ){

System. out. println ("array out-of-bounds error ");

}

System. out. println ("after an exception occurs ");

}

/* Output:

Before an exception occurs

Array out-of-bounds error

After frequent appearance

*/

The code is as follows: Copy code

Public static void testException2 (){

Int [] ints = new int [] {1, 2, 3, 4 };

System. out. println ("before an exception occurs ");

System. out. println (ints [4]);

System. out. println ("Do I still have the honor to execute it?"); // after an exception occurs, the code behind it cannot be executed.

}


 

First, point out the shortcomings in the example. IndexOutofBoundsException is a non-inspected exception, so try... catch... display capture, but my goal is to use different processing methods for the same exception to see what different results it will have (here we can only use it for a moment ). When an exception occurs, the first method only jumps out of the try block, but the code behind it will still be executed. However, the second method is not the same. It jumps out of the method and is tough. From the first method, we can see that try... catch... it is a kind of "transactional" protection. Its purpose is to ensure that the program runs normally, at the same time, it will also inform programmers of detailed information about errors in their programs (such details sometimes depend on the programmer's design ).

Example 2. Re-throw an exception

The code is as follows: Copy code


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 ("I don't know how to handle this exception or I don't want to handle it at all, but it is not suitable if I don't do it. This is to throw an exception and submit it to the next level for processing ");

// Throw an exception 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 exception is intended to be good. Let's try to fix the program, but in reality we have a low chance of fixing it. We often use it to record error information. If you get tired of handling exceptions and throw exceptions again, it may be a good relief for you. The exception was thrown to the upper-level and the caller. Let him worry about it. In this case, the java Exception (of course, the checked exception) brings us a lot of trouble, even though its starting point is good.

 

Example 3: abnormal link usage and loss

The code is as follows: Copy code

ExceptionA, ExceptionB, ExceptionC

Public class extends Tiona extends Exception {

Public region Tiona (String str ){

Super ();

}

}

 

Public class ExceptionB extends Tiona {

 

Public ExceptionB (String str ){

Super (str );

}

}

 

Public class ExceptionC extends Tiona {

Public ExceptionC (String str ){

Super (str );

}

}

 

Exception loss:

The code is as follows: Copy code

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 ");

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 does not I print ExceptionC instead? Let's analyze it by yourself!

The above situation is equivalent to missing an exception, which is very unfavorable in our troubleshooting process. What should we do when we encounter the above situation? This is the application of the exception chain: saves the exception information and does not lose the original exception when another exception is thrown.

The code is as follows: Copy code

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 ");

// Abnormal connection

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 feature of this exception chain is available for all exceptions, because the initCause () method is inherited from Throwable.

Example 4: Cleanup

Cleaning is essential for us because some resource-consuming operations, such as IO and JDBC, are required. If we do not close it right after it is used up, the consequences will be very serious, which means memory leakage. The emergence of exceptions requires that we have to design a mechanism to clean up resources in a timely and correct manner under any circumstances. This is finally.

The code is as follows: Copy code

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. It is an example of reading files. Such an example is also very common in JDBC operations. (So I think timely and correct resource clearance is one of the basic qualities of a programmer .)

The Try... finally structure is also a means to ensure that resources are properly closed. If you do not know what exceptions will occur during code execution and the resources cannot be cleaned up, use try to wrap this "suspicious" code, then, clear the resources in finally. For example:

The code is as follows: Copy code

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 ();

}


We should note the difference between this method and the previous method. The next person may get used to it better and close reader early. However, exceptions may occur at any time before reader. close (). Such a code structure cannot prevent exceptions. Because the program will jump out of the exception and the subsequent code cannot be executed (this should have been proved by the instance above ). Then we can use try... finally to transform it:

The code is as follows: Copy code

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 ();

}

}

Closing resources early is a good behavior, because the longer you forget to close resources, the more likely you are. In this way, try... finally will ensure that everything is safe (don't be too troublesome, java is just so reasonable ).

In another case, if I want to open a file in the constructor or create a JDBC connection, because we need to use this resource in other methods, therefore, you cannot close this resource early in the constructor. So we have no choice? The answer is No. Let's take a look at the following example:

The code is as follows: Copy code

Public class ResourceInConstructor {

BufferedReader reader = null;

Public ResourceInConstructor (){

Try {

Reader = new BufferedReader (new InputStreamReader (new 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 introduces a little more, but exceptions do seem to be easy to use. java still has many things to be dug up.

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.