Talking about Java exceptions [Exception]

Source: Internet
Author: User
Tags readfile throw exception throwable

A Definition of exceptions

In the Java programming idea, you define an exception: an issue that prevents the current method or scope from continuing to execute. Although there are exception handling mechanisms in Java, it is important to be clear that exceptions should never be viewed in a "normal" manner. The absolute point is that an exception is a kind of error, or a problem, that can cause a program to fail. Java to propose exception handling mechanism, is to tell the developer, your program appears abnormal situation, please note.

Remember when learning Java, the exception is always confused, do not know what the meaning of this anomaly, why there is this mechanism? But as knowledge accumulates, there is a sense of anomaly. Give an example to illustrate the purpose of the exception.

public class Calculator {public int devide (int num1, int num2) {//Determine if divisor is 0if (num2 = = 0) {throw new Illegalargumentexceptio N ("Divisor cannot be Zero");} return num1/num2;}}

Take a look at the methods of this class in addition to the operation, if you are a novice you may directly return to the results of the calculation, do not consider what parameters are correct, whether it is legal (of course, can be forgiven, who have come here). But we should think about it as well as possible, so that the "signs" that could lead to the failure of the program are stifled in the cradle, so it is necessary to examine the legality of the parameters. One of the parameters of the execution parameter check thrown out of the illegal exception, which belongs to this method of abnormal conditions. Under normal circumstances we will use the calculator correctly, but do not rule out carelessness to assign the divisor value to 0. If you have not considered this situation before and it happens that the user is not good at math, then you are finished. But if you have thought about this before, it is clear that the error is in your control.

Two Unusual literacy campaigns

Today, chatting with others to see a joke: The world's most true dependence, is you in try me in catch. No matter you send God horse temper, I silently bear, quietly handle. Most beginners feel about Java exceptions: Try...catch .... Yes, this is the most used, but also the most practical. My feeling is: Java exception is from "Try...catch ..." come.

First, familiarize yourself with the Java exception System:

The Throwable class is a superclass of all errors or exceptions in the Java language (this is what all can throw). It has two sub-classes: Error and exception.

Error: Used to indicate a serious problem that a reasonable application should not attempt to capture. This situation is a big problem, too big for you to deal with, so just do it, you don't have to worry about it. For example, Virtualmachineerror: This error is thrown when a Java virtual machine crashes or runs out of resources that it needs to continue to operate. Well, even if this anomaly exists, then when and how should we deal with it?? Give it to the JVM, no more professional than that.

Exception: It points out the conditions that a reasonable application wants to capture. Exception is divided into two categories: one is checkedexception, the other is uncheckedexception. The difference between the two types of exception is mainly checkedexception need to use try...catch ... The capture is displayed, while the uncheckedexception does not need to be captured. Usually uncheckedexception is also called RuntimeException. Effective Java states that using a checked exception (checkedexception) for recoverable conditions uses a run-time exception (RuntimeException) for a program error (the implication is unrecoverable and a blunder has been made).

Our common Runtimeexcepiton are illegalargumentexception, IllegalStateException, NullPointerException, Indexoutofboundsexception and so on. For those checkedexception, we are in the process of writing programs try...catch ... The catch exception is checkedexception. The IOException and its subclasses in the IO package are checkedexception.

Three Use of exceptions

In the exception of the use of this part of the main demo code, are we usually write code in the process will encounter (of course, only a small part), to stimulate it!

Example 1. This example shows the execution flow of the code after the exception by comparing two methods.

public static void TestException1 () {int[] ints = new int[] {1, 2, 3, 4}; System.out.println ("Pre-anomaly"); try {System.out.println (ints[4]); System.out.println ("I was fortunate enough to do it");//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 exception appears");} /*output: Exception occurred before array out of bounds error 4 after the occurrence of the exception */

  

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 an exception, the code behind him cannot be executed}

  

First point out the shortcomings of the example, Indexoutofboundsexception is a non-inspected exception, so do not try...catch ... Show snapping, but my goal is to treat the same exception in a different way, to see what it will look like (it's going to have to be done here). 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 not the same, just jump out of the way, more tough. From the first method we see that try...catch ... is a "transactional" guarantee, which is designed to ensure that the program runs in an abnormal situation, and that it tells the programmer the details of the error in the program (this detail is sometimes dependent on the programmer's design).

Example 2. To re-throw an exception

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 at all, but do not handle it is not appropriate, this is to re-throw exception to the previous level of processing");//re-throw exception 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 intention of the exception is good, let's try to fix the program, but in reality we have very little chance of fixing it, and many of the time we use it to keep track of the wrong information. If you're tired of dealing with exceptions, re-throwing exceptions can be a good relief for you. Leave this exception to the previous level, and throw it to the person who called the method, and let him take his mind. In this case, Java exceptions (which, of course, refer to exceptions) add a lot of trouble to us, even though the starting point is good.

Example 3. Use of abnormal chain and abnormal loss

Define three exception classes: 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);}}

Case of abnormal loss:

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. Exceptioncat 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 a lack of an exception, which is very bad in our troubleshooting process. What should we do when we meet the above situation? This is where the exception chain comes in: Save the exception information and throw another exception without losing the original exception.

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");//Exception even c.in Itcause (e); throw C;}} public static void Main (string[] args) {try {g ();} catch (Exceptionc e) {e.printstacktrace ();}}} /*exception. Exceptioncat exception. NEVERCAUGHT.G (Nevercaught.java:12) at exception. Nevercaught.main (nevercaught.java:21) caused by:exception. Exceptionbat exception. NEVERCAUGHT.F (Nevercaught.java:5) at exception. NEVERCAUGHT.G (nevercaught.java:10) ... 1 more*/

This exception chain is characterized by all exceptions, since the Initcause () method is inherited from Throwable.

Example 4. Cleanup work

Clean-up work is essential to us, because if some resource-consuming operations, such as IO,JDBC, are used. If we do not close in time after the use of the correct, the consequences will be very serious, which means a memory leak. The appearance of anomalies requires that we devise a mechanism in which resources can be cleaned up in a timely and correct manner, regardless of the circumstances. This is finally.

public void ReadFile (String file) {BufferedReader reader = null;try {reader = new BufferedReader (New InputStreamReader FileInputStream (file)),//Do some other work} catch (FileNotFoundException e) {e.printstacktrace ();} finally {try {Reade R.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 cleanup of resources is one of the basic qualities of a programmer.) )

Try...finally structure is also a means to ensure the correct closure of resources. If you are not sure what happens during the execution of the code will cause the resource not to be cleaned up, then you wrap the "suspicious" code with a try and then clean up the resource in the finally. To give an example:

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

Let's take a look at the difference between this method and the previous one, and the next person may get used to a little better and close reader early. But it often backfired, because it could happen at any time before Reader.close (), and such a code structure would not prevent any exceptions from appearing. Because the program jumps out where the exception occurs, the subsequent code cannot be executed (this should be durable on the instance above). Then we can use try...finally to transform:

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

Early closing of resources is a good behavior, because the longer you forget the more likely you are to shut down. This try...finally on the match to ensure that the foolproof (not too troublesome, Java is so serious).

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 this resource early in the construction method. So we're not going to get over it? The answer is in the negative. Take a look at the following example:

public class Resourceinconstructor {BufferedReader reader = Null;public resourceinconstructor () {try {reader = new Buffere Dreader (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 is a bit more, but the exception is really easy to use to look at things, Java still have a lot of things to dig deep.

Four Misuse of the exception

For the misuse of the exception is very common, the last part has listed a few, we look carefully. Let's talk about two other.

Example 1. With a exception to catch all the anomalies, quite "Wan Fumo Fumo opens" boldness. But it's also the stupidest act.

public void ReadFile (String file) {BufferedReader reader = null;  Connection conn = null;try {reader = new BufferedReader (new InputStreamReader (file));//Do FileInputStream other Workconn = Drivermanager.getconnection ("");//...} catch (Exception e) {e.printstacktrace ();} finally {try {reader.close (); Conn.close ();} catch (Exception e) { E.printstacktrace ();}}}

  

From an unusual point of view, such strict procedures are indeed foolproof, and all anomalies can be captured. But from the programmer's point of view, in case the program goes wrong, how do we tell if it's what caused it, io or jdbc ... Therefore, this writing is worth a counter-example. Let us not think that this is naïve and that fools will do it. I did see a similar situation when I was practicing at the company: it was just someone who didn't use exception but throwable.

Example 2. Here is not an example, the above procedures are counter-examples. Exceptions are the mechanism by which programs handle unexpected situations, and we need to get as many unexpected information as possible, including the location, description, reason, and so on, when something happens to the program. These are all clues to our problem solving. But the above example is just a simple printstacktrace (). If we write the code ourselves, we need to describe the exception as much as possible. For example, why this exception occurs, and in what circumstances this exception occurs. If the parameter passed in the method is incorrect, tell what argument is a valid parameter, or give a sample.

Example 3. Write the try block short, not all of the things are left here, we as far as possible to analyze the exactly which lines of the program may be an exception, just to the possible exception of the code to try. Try to write a try...catch for each exception to avoid abnormal loss. In IO operations, a ioexception also has the boldness of "Wan Fumo Fumo opens".

Five Summarize

The summary is very simple, do not use exceptions in order to use exceptions. Exceptions are part of the program design and are designed to be more sophisticated.

Http://www.cnblogs.com/focusj/archive/2011/12/26/2301524.html

Talking about Java exceptions [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.