Java – where and how are exceptions used?

I'm reading about exception handling in Java so that I can write better code OK, I admit I'm guilty. I used too many try catch {} blocks. I used ex.printstacktrace() in catch and didn't even use the correct recorder (in fact, system.out and system.err were redirected to printwriter, so the log was generated) However, after several hours of reading, I found myself in a strange place: unknown If an exception is designed to convey information about the flow of exception States, how do you know where is the correct level of that information?

For example, when a database error occurs, should it return a null value, an error code, or throw an exception? If thrown, should where handle this exception? I understand that if you can't do anything, even recording exceptions is useless However, in GUI applications, this may easily kill your GUI (I use SWT, which I often see), even in the case of menu method () (the arrayindexoutofbounds exception will close the application if it is not handled) This example can last forever, but here is a summary of the problem:

>Does the use of try catch () have a negative impact on performance? > Is it best to use specific exception types? What if I miss one? Possible X-type exceptions? Frankly, in 2 – 3 years, I've heard that only 10% of Java standard exceptions are used Yes, some people say that if the caller doesn't know how to handle the thrown exception, he should have no right to call it a throw method Is that right? > I have read this article Anders Hejlsberg, saying that checking exceptions is bad Does this mean that convenient abnormal swallowing is recommended in some cases? > The picture is worth 1000 words; I think some examples will help a lot here

I know this topic is eternal, but in fact, I look forward to using 150 courses to examine a medium-sized course and use your opinions Thank you.

Solution

The exception is that a task programmer does not have to deal with the problem himself (1) : if the problem has no logic, give him the task

(2) : he can't handle (not enough information) files that have never been found and the task of reading strings from files may require the user to select another file, but now the task may be the file extension or what folder I don't know how the task creates a GUI to ask again

(3) : there is no logical (or manageable) way to distinguish between different returns If the task cannot read the file and returns null What if the file format is wrong and null is returned? What's the difference between the two? Exceptions can be used to distinguish Why is it called exception: - D

(4) : there are many similar tasks that require similar processing and writing and are difficult to maintain in all tasks Writing all access handle code can be confusing because you may need a lot of repetition

interface DBAccess {
    public Result accessDB();
}

class DBOperation {
    static public void DoOperation(DBAccess pAccess) {
        try { return DBAccess.accessDB(); }
        catch(InvalidDBPasswordException IPE) {
             // Do anything about invalid password
        }
        catch(DBConnectionLostException DBCLE) {
             // Do anything about database connection lost
        }
        // Catch all possible DB problem
    }
}

...

private User[] ShowUserList_and_ReturnUsers() {
    // Find the used.

    // Show user list

    if (Users.count() == 0)
         return null;
    else return Users;

    // No need to handle DB connection problem here
}
private User[] GetUserProfile() {
    // Find the used and return
    // No need to handle DB connection problem here
}
...

/** An onClick event to show user list */ {
    DBOperation.DoOperation(new DBAccess() {
        public Result accessDB() {
            return ShowUserList_and_ReturnUsers();
        }
    });
}
/** An onClick event to show a user profile */ {
    DBOperation.DoOperation(new DBAccess() {
        public Result accessDB() {
            return GetUserProfile();
        }
    });
}
... Many more DB access

(5) : write out all tasks to check whether errors are complex or slow down The above questions should show how to help reduce complications This is how it helps not to slow down

for(int i = 0; i < Users.length; i++) {
    User aUser = Users[i];
    // Do something with user
}

Replaced with

try {
  for(int i = 0; ; i++) {
      User aUser = Users[i];
      // Do something with user
  }
}
catch(ArrayOutOfBoundException AOBE) {}

If the number of users is large, the replacement code will be better

When a database error occurs, you should return a null value and issue an error code or throw an exception? A: it depends on what kind of mistake Yes, if you can't find a user, it's not a mistake However, if the password is incorrect or the connection is incorrect, these errors are because trying to handle it in a normal way will complicate the program

(1). Does using too much try catch () have a negative impact on performance? A: according to "effective Java", as long as I remember (I don't have this book now), it has a very small impact (bad loop)

(2). Is it better to use specific exception types? A: one of the best user - specific is to avoid solving wrong problems

What if I miss the possible X-type exception that may occur? Frankly, I've heard and used 10% of Java standard exceptions in 2-3 years A: just like dealing with errors, you can also miss them When you find it, you just need to add it

Yes, some people say that if the caller doesn't know how to deal with the excluded exception, he should have no right to call it throwing method Is that right? A: No, if I don't know how to handle some exceptions, throw them again

(3). I have read this article by Anders Hejlsberg and said that the exceptions to inspection are bad Does this mean that convenient abnormal swallowing is recommended in some cases? A: I think he's talking about "checking exceptions" as a function of the compiler to ensure that some exceptions should be handled Have abnormal ideas

(4). A picture is worth 1000 words I guess here are some examples that will help a lot Answer: the above code

I've got to run now Sorry...: -p (in a minute, honey!)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>