简体   繁体   English

异常处理

[英]Exception Handling

catch (Exception ex)
{
    DBGlobals.Error("OHMjson.Graph.saveLastGraphName - Error: " + ex.getMessage());
    msg = "Unable to save data";
    status = false;
}

This piece of code would throw an status as false, if i encounter an error. 如果遇到错误,这段代码会将状态设置为false。

Instead should i thrown New exception. 相反,我应该抛出新的异常。 Is this the right way. 这是正确的方法吗? How can i handle exception in a better way. 我怎样才能以更好的方式处理异常。

Prefer throwing exceptions to returning error codes/status. 首选抛出异常以返回错误代码/状态。

Returning an error code means the caller should always remember to check for it. 返回错误代码意味着调用者应该始终记得检查它。 Throwing the exception allows the calling code to make the decision of what to do (an normally the higher up the decision, the better it can be made). 抛出异常允许调用代码决定做什么(通常决策越高,就越好)。

First, don't catch Exception . 首先,不要捕获Exception Catch a specific subclass. 捕获特定的子类。

Second, yes it may be that an underlying IOException , which is what this looks like, should be wrapped in an app-specific exception. 第二,是的,可能是底层的IOException ,它看起来像这样,应该包含在特定于应用程序的异常中。 You could have, for instance: 你可以,例如:

final class DBGlobalsException extends Exception
{
   Field somethingDBGlobalsSpecific;

   //where this is shorthand for chained constructors that look like Exception
   DBGlobalsException(String message, Throwable cause)
   {
     super(message,cause);
   }

   // elaborate your exception with whatever error state you want to propagate outwards
   void setField(Field ...) {}
}

And you could then 然后你就可以了

catch (IOException ex) {
   DBGlobals.Error("OHMjson.Graph.saveLastGraphName - Error: " + ex.getMessage());
   msg = "Unable to save data";
   status = false;
   DBGlobalsException dbe = new DBGlobalsException(msg,ex);
   dbe.setField(status /* or whatever */);
   throw dbe;
}

See also: Throwing Exception , Throwing new and old exceptions , Rolling your own . 另请参阅: 抛出Exception抛出新旧异常滚动自己的 异常 That's just a few, there are a bunch of great SO Q+A's on exception handling, chaining, etc. Some useful best-practices stuff outlined at WikiBooks . 这只是一些,在异常处理,链接等方面有一堆很棒的SO Q + A.在WikiBooks上概述了一些有用的最佳实践内容。

Also read Oded's answer and think it through... your exception should encapsulate whatever status (error codes, flags, etc...) are required for the outer code to recover from the condition -- or it should be an unrecoverable condition (see RuntimeException ). 还要阅读Oded的答案并仔细思考......你的异常应该封装外部代码从条件中恢复所需的任何状态(错误代码,标志等等) - 或者它应该是一个不可恢复的条件(参见RuntimeException )。

Finally, the canonical Effective Java reference: Item 43: Throw Exceptions Appropriate to the Abstraction . 最后,规范的有效Java参考: 第43项:抛出适用于抽象的例外

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM