"Getting Started with Java" DAY16 Java exception handling (top)

Source: Internet
Author: User
Tags arithmetic throw exception

When when when, you crossing, long time no see, very miss.

Today we're going to talk about a leprechaun in Java, that's the anomaly.

What is an exception? What is exception handling?

Exception, as the name implies is not normal, (escape), is the Java program run, the unexpected things happen, it prevents the program according to the programmer's expected normal execution.

Exception handling, should say exception handling mechanism, is specially used to subdue this goblin magic weapon. The exception handling mechanism in Java allows the program to handle exceptions in the event of an exception, in accordance with the code's pre-set exception handling logic, so that the program can get back to normal and continue executing, and keep the code clear.

In short, Java exception handling allows us to proactively tackle possible anomalies and handle them in a rounded fashion.

Let's look at a little chestnut and see what the anomaly looks like in Java.

 Public class Test {    publicstaticvoid  main (String args[]) {        int i = 0 /0;        System.out.println ("i =" + i);}    }

  

Don't panic don't panic, do not see the red hint of heart collapse just want to turn off the IDE, come, hold my hand, take you to see "abnormal" This torture Goblin's true face (funny).

The code has 0 as the denominator, so the program will have an arithmetic exception, throw an exception, if there is no processing, the default will terminate the program, so the subsequent print content does not output. In the exception content, there is a description of the exception type: Java.lang.ArithmeticException, which is the arithmetic exception, followed by the exception reason:/by zero, that is, the reason for the exception is the 0 as the denominator, and there is a stack of information behind, It is pointed out that the exception is thrown in the Com.frank.chapter16.main.Test.main under this package, the Test class of the 11th line (the number of rows if you think not the same, do not care, because my code before the beginning of some non-descriptive information), because there is only one method call, so there is no Very long stack information, and it looks very concise and straightforward.

So you see, in fact, the exception is not so scary, not only to the abnormal reason, but also told you this bug is out in the first few lines, so make good use of it, can help you write more difficult to find the bug, Yuck, said wrong, can help you more easily find the bug (manual funny).

If you do not want to throw an exception after the program ends, but want it to continue to run it? Then capture it.

How to use exception handling

Let's change the chestnut above:

 Public class Test {    publicstaticvoid  main (String args[]) {        try {            int i = 0/0;        } Catch (Exception e) {            System.out.println ("It seems to be an exception, but I don't care, I still have to run");        }        System.out.println ("finished running!") );    }}

The output is as follows:

It seems to be an exception, but I don't care, I have to continue running run finished!

OK, very strong, now even if the exception is thrown, the program continues to run. An anomaly is like a beast, but once you capture it and tame it, you can use it as you please.

Try...catch ... is a common exception handling collocation, if an exception occurred in the TRY statement block, if the exception is caught, then it will jump directly into the catch statement block, execute the code in the catch statement, like the chestnut above, because the exception class is captured processing, So when its subclass exception Java.lang.ArithmeticException is thrown out, it can also be captured. The structure hierarchy relationship of exception class is discussed in detail later.

There is another way, that is, the try...catch...finally,finally statement block is more powerful than the catch, said the catch statement block must be captured to a specific exception to execute the code inside, If the catch is arithmeticexception but throws a null pointer exception, it will not be caught and the exception will be gone. At this point, finally the advantage is shown, no matter what kind of exception thrown, and whether or not to throw an exception, finally the code will be executed. So the general usage is to release the resources that need to be freed in the finally statement block, such as the socket connection, close the IO stream, close the database connection, and so on. In other words, usually in the finally clean up try to throw in the mess, distressed a second finally, sure enough ANI ah.

Of course, try...finally such a collocation is OK, it is important to note that when an exception occurs in the Try statement, the code after the exception occurs will not be executed, but instead jumps to the corresponding Catchu or finally.

 Public classTest { Public Static voidMain (String args[]) {Try{            inti = 0/0; }Catch(NullPointerException e) {System.out.println ("Catch null pointer exception here"); }Catch(ArithmeticException e) {System.out.println ("Catch arithmetic anomalies here"); }finally{System.out.println ("This is finally."); } System.out.println ("Finished running!"); }}

The output is as follows:

Here 's the catch arithmetic anomaly here is finally run complete !

In the above code, the catch statement block can be used multiple at the same time, the first catch statement block captures a null pointer exception, but because it throws an arithmetic exception, it is not captured, but caught by a second catch, so the code in the second catch statement block executes. The exception match is matched in order from top to bottom, and the code block in finally is executed. There is also a very interesting return question about try...catch...finally, if there is a return in the three statement block, what will the final result be? Here is a detailed explanation, http://www.cnblogs.com/mfrank/p/7895660.html is interested in the words can take a look.

In most cases, the code in finally will be executed, and in one case, the code in the finally will not be executed, which is to end the virtual machine in the TRY statement block (e.g., using system.exit (0); )。

On the exception, there is a keyword to be introduced, that is, throw, use throw can be thrown to throw an exception. See this you may be the face of a crazy, the initiative to throw??? Not enough, not too much, not too much to join the fun? Don't worry, there must be some misunderstanding in the middle, put down the knife, have words to say well.

The Throw keyword is really used to throw an exception, and you can use it like this:

 Public class Test {    publicstaticvoid  main (String args[]) {        try {            thrownew nullpointerexception ("I hear you're busy, throwing an exception to you.") ");        } Catch (NullPointerException e) {            System.out.println ("catch null pointer exception here, prompt content:" + e.getmessage ());            E.printstacktrace ();     }}}

The output is as follows:

here to catch a null pointer exception, prompt content: I heard that you are very busy, throw an exception to you. Java.lang.NullPointerException: I heard you are very busy, throwing an exception to you. At    Com.frank.chapter16.main.Test.main (Test.java:11)

Throw keyword can throw any type of exception, of course, you want to, and throw error, as for what is error, has been with the exception relationship, will be explained in the next article. Don't delve into it for the moment.

In the throw exception, you can add the cause of the exception, which makes it easier to locate the problem, of course, it is generally not used like pest, here just for the sake of simplicity.

To this end, the first half of the exception has been explained in this article, explaining what is an exception, what is exception handling, and how to use the exception handling mechanism. I believe you have a preliminary understanding of this Goblin, the next article, will explain the exception family members, how to use the custom exception, has been abnormal handling of the actual use of the correct posture. Welcome to continue to pay attention to, after the plan of more than two weekly updates, if there are explanations missing or bad place, welcome to point out in time, common progress!

"Getting Started with Java" DAY16 Java exception handling (top)

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.