java:不能重新启动异常:未处理的异常类型异常 [英] java: can't rethrow exception: Unhandled exception type Exception

查看:256
本文介绍了java:不能重新启动异常:未处理的异常类型异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想捕捉一个例外,记录它,设置一个标志,并重新启动相同的例外

I'd like to catch an exception, log it, set a flag, and the rethrow the same exception

我有这个代码:

public Boolean doJobWithResult() {
    boolean result = true;
    final Feed feed = Feed.findById(feedId);
    try {
        feed.fetchContents();
    } catch (Exception ex) {
        result = false;
        Logger.info("fetching feed(%d) failed", feedId);
        throw ex;
    }
    return result;
}

但是,eclipse在throw ex中抱怨说,未处理的异常类型异常并建议我在它周围添加一个try-catch块。

But eclipse complains at throw ex, telling that "Unhandled exception type Exception", and suggests me to add a try-catch block around it.

其实我想要这个进程调用这个方法来处理异常,而不是自己处理。如果一切顺利,我只想返回true,如果有异常,则记录它。

In fact, I want the process calling this method to handle the exception, and not handle it myself... I just want to return true if everything goes ok, and log it if there's an exception

另一方面,我可以将异常包装在另一个异常中,但是不能扔同一个..

On the other hand, I can wrap the exception inside another exception, but I can't throw the same one..

任何想法?

推荐答案

p>我认为这里有很多不同的东西:

I think there are various things to mention here:


  1. 你要么要$ doJobWithResult()在成功时返回true,在失败时返回false,或者在成功时返回任何值,并在失败时抛出异常。
    两者同时是不可能的。在第一种情况下,捕获异常,记录并返回false,在第二种情况下,更改您的签名以返回 void 并抛出一个异常,在呼叫者中处理它。

  2. 这是一个不要来捕获异常,记录并重新抛出异常。为什么?因为您的方法的潜在呼叫者不知道您已经登录了它,并且也记录它。
    抛出异常(在这种情况下,调用者必须处理它)或者抓住它并处理它(记录它)。

  3. 请注意,抛出异常不会给你的方法的调用者任何关于你的方法可能会出错的线索,总是更好地抛出更多的特定的异常,或者在一个用户定义的异常中包装一个异常,

  4. 此外,如果您抛出异常,调用者可能会试图捕获异常没有注意到这也将捕获每个RuntimeException(因为它从异常导出),这可能不是所期望的行为。

  1. You either want doJobWithResult() to return true on success and false on failure, or return nothing on success and throw an exception on failure. Both at the same time is not possible. In the first case, catch the Exception, log it and return false, in the second case change your signature to return void and throw an exception and handle it in the caller.
  2. It's a Don't to catch an exception, log it and rethrow it. Why? Because a potential caller of your method does not know that you are already logging it, and migh log it as well. Either throw an exception (in which case the caller has to deal with it) or catch it and handle it (log it).
  3. Note that throwing Exception does not give the caller of your method any clue about what might potentially go wrong in your method, it's always better to throw more specific exceptions, or to wrap an exception in a user-defined one and rethrow it.
  4. Moreover, if you throw Exception, a caller might be tempted to catch Exception without noticing that this will also catch every RuntimeException (since its derived from Exception), which might not be desired behavior.

这篇关于java:不能重新启动异常:未处理的异常类型异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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