Java - 异常在哪里和如何使用? [英] Java - where and how should exceptions be used?

查看:134
本文介绍了Java - 异常在哪里和如何使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读一些有关Java中的异常处理的内容,以便能够编写更好的代码。好的,我承认我有罪我使用了太多的try-catch {}块,我在catch中使用了 ex.printStackTrace(),甚至没有使用正确的记录器(实际上是 System.out System.err 被重定向到一个 PrintWriter 因此生成日志)。然而,经过几个小时的阅读,我发现自己在一个陌生的地方:未知数。如果异常被设计为传递有关异常状态流的信息,那么如何知道WHERE是该信息的正确级别?



例如,当发生数据库错误时,应该返回一个空值还是一个错误代码,还是抛出异常?如果抛出,WHERE应该处理这个异常吗?我明白,如果您不能做任何事情,即使记录异常也是没有用的。然而,在GUI应用程序中,这可能会很容易地杀死你的GUI(我使用SWT,我经常看到这个),即使是 menuShown()方法的情况(一个 ArrayIndexOutOfBounds 异常将关闭应用程序,如果不处理)。这个例子可以永远存在,但这里是问题的总结:


  1. 使用try-catch()过度对性能有负面影响?

  2. 最好使用特定的异常类型吗?如果我错过了可能发生的可能X类型异常的一个
    怎么办?

    坦白说,我已经听说过,只使用了10%的Java标准异常, 2-3年是的,有人说如果调用者不知道如何处理抛出的异常,他应该没有权利称之为投掷方法。这是正确的吗?

  3. 我已经阅读了这篇文章:安德斯
    Hejlsberg
    ,说检查的异常是坏的。是否表示在某些情况下是否建议方便的异常吞咽?

  4. 图片价值1000字;我想有一些例子会帮助很多的
    这里。

我知道这个主题是永恒的,但实际上我很期待使用您的建议审查150个班级的中等规模项目。非常感谢。

解决方案

异常是这样的,所以任务的程序员不必自己处理这个问题。 (1):如果问题没有逻辑给他处理任务。
从流读取一个字符串的任务不应该处理磁盘错误是不是的。但是如果数据不包含字符串,则应该是非常合乎逻辑的。



(2):他无法自己处理(没有足够的信息)
从未找到的文件和文件中读取字符串的任务可能会要求用户选择另一个文件,但是现在该任务现在可以是什么文件夹可能是文件扩展名的文件夹。不知道这个任务如何创建一个GUI来重新询问。



(3):没有逻辑(或可管理的)方式区分不同的返回。
如果任务无法读取文件并返回null。如果文件格式错误,返回null呢?这两者有什么不同?异常可以用来区分。为什么它被称为异常:-D。



(4):有许多类似的任务需要类似的处理和写入,在所有任务中难以维护。
编写所有访问的句柄代码可能会混乱,因为您可能需要许多重复。

  
接口DBAccess {
public Result accessDB();
}

class DBOperation {
static public void DoOperation(DBAccess pAccess){
try {return DBAccess.accessDB(); }
catch(InvalidDBPasswordException IPE){
//对无效密码执行任何操作
}
catch(DBConnectionLostException DBCLE){
//对数据库连接丢失任何事情
}
//捕获所有可能的DB问题
}
}

...

私人用户[] ShowUserList_and_ReturnUsers( ){
//找到用过的。

//显示用户列表

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

//不需要在这里处理数据库连接问题
}
私人用户[] GetUserProfile(){
//查找使用并返回
//不需要处理数据库连接问题
}
...

/ **显示用户列表的onClick事件* / {
DBOperation.DoOperation (new DBAccess(){
public Result accessDB(){
return ShowUserList_and_ReturnUsers();
}
});
}
/ **显示用户配置文件的onClick事件* / {
DBOperation.DoOperation(new DBAccess(){
public Result accessDB(){
return GetUserProfile();
}
});
}
...更多数据库访问

(5):写所有检查错误使任务复杂或减慢。
上述问题应该显示如何帮助减少并发症。这是如何帮助不要减速的。

  

for(int i = 0; i < Users.length; i ++){
用户aUser = Users [i];
//用户
}执行某些操作

替换为

try {
for(int i = 0;; i ++){
用户aUser = Users [i];
//用户
}
}
catch(ArrayOutOfBoundException AOBE){}

如果用户数量较大,替换代码将会更好。






当发生数据库错误时,应该返回一个空值,并且出现错误代码还是抛出异常?
答案:根据什么样的错误。喜欢,如果你找不到一个用户,那不是错误。但是,如果密码错误或连接不正确,这些错误就是以正常方式处理它,使程序复杂化。



(1)。使用过多的try-catch()对性能有负面影响?
答案:根据有效的Java,它具有非常非常小的效果(只有不好的循环),只要我记得(我现在没有这本书与我在一起)。



(2)。
使用特定的异常类型更好?
答案:用户特定的一个更好地避免解决错误的问题。



如果我错过了可能发生的X类型的异常之一,该怎么办?坦白说,在2-3年内,我听说过只使用了10%的Java标准异常。
答案:就像处理错误一样,你也可以错过。是的,有人说如果调用者不知道如何处理被剔除的异常,那么他应该没有称为投掷方法的权利。是对的吗?
答案:不,如果我不知道该如何处理某些异常,请重新抛出。



(3)。我已经阅读了Anders Hejlsberg的这篇文章,说检查的例外是坏的。是否表示在某些情况下是否建议方便的异常吞咽?
答案:我认为他正在谈论检查异常作为编译器的一个功能,以确保一些异常应该被处理。有例外的想法。



(4)。一张图片价值1000字。我想有一些例子会帮助很多。
答案:上面的代码。



我现在得到了运行....对不起... :-p(在一分钟内,亲爱的! !)


I was reading some things about exception handling in Java, to be able to write better code. OK, I admit, I am guilty; I've used too much try-catch{} blocks, I've used ex.printStackTrace() in the catch, not even using a proper logger (actually the System.out and System.err were redirected to a PrintWriter, so a log was generated). However, after a few hours of readings, I find myself in a strange place: the unknown. If the exceptions are designed to pass info about abnormal states of flow, how does one know WHERE is the proper level to do something with that info?

For instance, when a database error occurs, should one return a null value or an error code, or throw the exception? If thrown, WHERE should that exception be handled? I understand that is no use even to log an exception if you cant do anything about it. However, in GUI apps, that could easily kill your GUI (I am using SWT and I've seen this too often), even for the case of the menuShown() method (an ArrayIndexOutOfBounds exception will close the app, if not handled). The example could go on forever, but here's the summary of questions:

  1. Does using try-catch() excessively have a negative impact on performance?
  2. Is it better to use specific exception types? What if I missed catching one of the possible X types of exceptions that could occur?
    Frankly, I've heard of and use a mere 10% I think of the Java standard exceptions, in 2-3 years. Yes, someone said that if the caller don't know how to deal with the thrown exceptions, he SHOULD NOT HAVE THE RIGHT to call the throwing method. Is that right?
  3. I've read this article of Anders Hejlsberg, saying that checked exceptions are bad. Should that indicate that convenient exception swallowing is advised in some cases?
  4. A picture is worth 1000 words; I guess some examples will help a lot here.

I know the subject is eternal, but actually I am looking forward to review a middle-size project of 150 classes, using your advice. Many thanks.

解决方案

Exception is there so the programmer of a Task does not have to deal with the problem by himself. (1): In case the problem is NOT LOGICAL to him to handle in the Task. A task to read a String from a stream should not handle disk error isn't it. But it should be very logical to handle if data does not contain a String.

(2): He can't handle it by himself (not enough info) A task to read a String from a file and file not found may ask user to select another file but how can the task now what folder the file might be what extension the file might be. Without knowing that, how can the task create a GUI to re-ask that.

(3): There is no logical (or manageable) way to distinguish between different return. If a task can't read the file and return null. What about if the file in the wrong format, return null too? How can these two differ? Exceptions can be used to differ that. That why it is called an Exception :-D.

(4): There are many similar tasks that need similar handling and writing that in all tasks is hard to maintain. Writing the handle code for all access can be a mess as you may require many duplications.


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): Writing all the checking for error complicate or slow down the task. The above problem should show how can it help reduce the complication. Here is how it help 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) {}

The replacement code will be better performance if the number of user is large.


When a database error occurs, should one return a null value, and error code or throw the exception? Ans: Depending on what kind of error. Like if you can't find a user, that is not an error. But if the password is wrong or the connection is down, these are errors as trying to handle it in a normal way complicate the program.

(1). Using excessive try-catch() has a negative impact on performance? Ans: According to "Effective Java", it has very very tiny effect (only not good in loop) as far as I remember (I don't have the book with me here now).

(2). Using specific exception types is better? Ans: User specific one is better to avoid solving the wrong problem.

What if i missed to catch one of the possible X types of exceptions that could occur? Frankly, I've heard and use a mere 10% i think of the Java standard exceptions, in 2-3 years. Ans: Just like if you handle the error without exception, You can miss it too. You simply add it in when you find that out.

Yes, someone said that if the caller don't know how to deal with the trowed exceptions, he SHOULD NOT HAVE THE RIGHT to call the throwing method. Is that right? Ans: No, if I don't know what to do with some exception, re-throw it.

(3). I've read this article of Anders Hejlsberg, saying that checked exceptions are bad. Should that indicate that convenient exception swallowing is advised in some cases? Ans: I think he is talking about "Checking exception" as a feature for the compiler to ensure that some exception should be handle. The the idea of having exception.

(4). A picture is worth 1000 words..i guess some examples will help a lot here. Ans: The code above.

I got the run now .... Sorry ... :-p (Be there in a minute, honey!!)

这篇关于Java - 异常在哪里和如何使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆