Java Programming Idea (11)--by exception handling error (2)

Source: Internet
Author: User

The previous article mentioned the basic concept of the anomaly and the reason for its use, the latter section is more difficult, and then separate write out.


1) finally clean up

For some code, regardless of whether the try has no throw, want to execute, in order to this can be at the end of the exception processing to add finally statement. The deepest impression is that when dealing with the database, finally always remember to recycle connection and so on.

In this way, the finally clause is always executed regardless of whether the exception is thrown. This is not afraid of the memory of the resources have been occupied, impressed with the teacher, the company a new to forget to write finally statement, the memory of more and more things, the whole system died.


There is a special one in which the return statement in the try will continue to execute the statement in the finally.


Deficiency: Abnormal loss

Class Importantexception extends exception{public    String toString () {        return ' import ';    }} Class Lightexception extends exception{public    String toString () {        return ' light ';    }} public class Loseexception {    static void I () throws importantexception{        throw new Importantexception ();    static void L () throws lightexception{        throw new Lightexception ();    }    public static void Main (string[] args) {        try{            try {                I ();             } finally{                L ();}         } catch (Exception e) {            e.printstacktrace ();}}    }

Important's exception is lost, although the author of the book has long hoped that the future version will fix the problem, but the current version of 7 has not improved AH.

In addition, the finally clause will also lose the exception with return.


2) constructor problem

The problem is more complicated, it's been a long time, not the same as before.

In the book, the constructor will set the object to a safe initial state, but there will be other actions, such as opening a file, which is only cleaned after the object is used and the user invokes a special cleanup method.

Why is it not the same as before, it is really like the author said, with finally the final processing. But, the constructor fails when it is created?


<span style= "FONT-SIZE:18PX;"    >public class TestConstructor {private BufferedReader BF; Public TestConstructor (String name) throws exception{try {bf = new BufferedReader (new FileReader (name)        );            } catch (FileNotFoundException e) {System.out.println ("Can not open!");        Actually not open, do not need to close throw e;            } catch (Exception e) {try{bf.close ();            }catch (IOException IE) {System.out.println ("close faild");        }}finally{//Do not close here}} public String GetLine () {string S;        try {s = bf.readline ();        } catch (IOException e) {throw new RuntimeException ("GetLine failed!");      } return s;            } public void Dispose () {try {bf.close ();        System.out.println ("dispose successful"); } catch (IOException e) {throw new RuntimeException ("GetLine FAILed! ");}}} </span>


Io Stream, the constructor after the parameter can be filereader and bufferedreader together, can not understand the words in advance to turn over the contents of Io stream. FileNotFoundException, in fact, the files can not be found, we do not have to clean up, because finally in every time the constructor is completed to execute once, can not write the closed statement here, why and before the code to clean up the last write in the finally different?

For different purposes, here we need the TestConstructor object to be open throughout the life cycle. And what we were hoping for was to hurry up and close.


There is also a special place where the string is to be initialized, but because the exception throws can not be initialized. When you really don't have to testconstructor, call the Dispose method to clear it.


<span style= "FONT-SIZE:18PX;" >public class Clean {public    static void Main (string[] args) {        try {            TestConstructor tc = new Testconstruct or ("A.txt");            try{                String S;                int i;                while ((s = tc.getline ())!=null) {                    //own character processing                }            }catch (Exception e) {                e.printstacktrace ();            } finally{                tc.dispose ();            }        } catch (Exception e) {            e.printstacktrace ();        } finally{            System.out.println ("Failed constructed!");}}    </span>

This nesting is written on its own, and eclipse does not give hints because the statement is already inside a try block. Careful analysis, this nesting is very beautiful, because the construction failed, we do not need to close the testconstructor, on the contrary, the construction succeeds, we finally remember to clean up, this and the above red Letter place is corresponding, TestConstructor is read the file, We do need to open the entire life cycle, and the clean class is called testconstructor, and when the string is successfully constructed and used, it is automatically closed with Dispose, but I didn't notice it when I wrote the program. Finally the processing and try,catch nesting can write so beautiful, really let a person simply astounding.


3) Exception Matching

This problem is relatively simple, after the exception is thrown, find a matching handler, it is considered that the exception will be processed, no longer continue to look for.

try {} catch (FileNotFoundException e) {   System.out.println ("Can not open!");} catch (Exception e) {}
if the exception matches the first one, then the capture, if not, is captured by exception, because exception captures exception and other exceptions derived from it.


Other options available:

Exception handling a principle is "only you know how to handle to catch the exception", the previous article has said that the exception is actually in order to place the error occurred in the code and the code to handle the error, let you focus on the former code.


The author himself has made a mistake:

    try{    }catch (Exception e) {}
Called: harmful if swallowed, swallowed harmful, abnormal has, because catch is must add, but there is no processing, it was swallowed. So, either write the wrong deal or throw it at the top.

4) History and perspective

History will not say, the book is too long.

Talk about a CLU designer's point of view-- We think it's unrealistic to force programmers to provide handlers when they don't know what's wrong . But we also know that it is unrealistic to ignore it, it is my own words, so the exception is a good thing.


Summary: Exceptions allow us to focus on the problem, that is, the code of the problem and business logic is separated and then centralized.

Take a look at the book's Exception Usage guide:

Try to finish what the current operating environment can do, and then throw different or identical exceptions to the higher level.

Make class libraries and programs more secure.

As an integral part of programming, learn to use it.

Java Programming Idea (11)--by exception handling error (2)

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.