简体   繁体   English

如何在Java中传播来自重写方法的异常

[英]How to propagate exception from an overridden method in Java

What is the best practice to terminate the execution of an overridden method? 终止执行重写方法的最佳做法是什么? Here is the example code that explains the context: 以下是解释上下文的示例代码:

@Override
protected String doInBackground(String... params) {

    URL serverURL = null;
try {
        serverURL = new URL((urlString));

    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
...
...

return response.toJSONString();
}

In the above code snippet, I am forced to catch MalformedURLException, so I used the try catch block. 在上面的代码片段中,我被迫捕获MalformedURLException,所以我使用了try catch块。 If that exception occurs, I would like to skip all the code below the catch block and propagate either the same exception or a different one that I would throw within the catch block until all the way to the Main method, hopping through the catch blocks and skipping the code in the middle in all the calling methods. 如果发生异常,我想跳过catch块下面的所有代码并传播相同的异常或我将在catch块中抛出的另一个异常,直到一直到Main方法,跳过catch块和在所有调用方法中跳过中间的代码。 How to do this? 这个怎么做?

The problems are: 1) I cannot add throws clause to the method signature because it is overridden and the base class doesn't allow it. 问题是:1)我不能将throws子句添加到方法签名中,因为它被覆盖并且基类不允许它。

2) Since the method has to return a String, I have to specify the return statement after the catch block.(What do I return if an exception has occurred?) 2)由于该方法必须返回一个String,我必须在catch块之后指定return语句。(如果发生异常,我该返回什么?)

3) Use System.exit in catch block - As some other posts on this forum point out, that may not be a good practice when you want your code to be reusable. 3)在catch块中使用System.exit - 正如此论坛上的其他帖子所指出的那样,当您希望代码可重用时,这可能不是一个好习惯。

The best practice for such a case would be to wrap the MalformedURLException with a RuntimeException : 这种情况的最佳实践是使用RuntimeException包装MalformedURLException

catch (MalformedURLException ex) {
    throw new RuntimeException("Failed constructing URL", ex);
}

Ideally, you'd really like to edit the method's throws clause so it can accommodate any exceptions that are likely to stem from overrides; 理想情况下,您真的想编辑方法的throws子句,以便它可以容纳任何可能源于覆盖的异常; but since this is impossible in your case (as per your conditions), the above seems most reasonable to me. 但是因为在你的情况下这是不可能的(根据你的条件),上面对我来说似乎是最合理的。

A related best-practice would be to avoid logging the exception before wrapping it. 一个相关的最佳实践是避免在包装之前记录异常。 From a design perspective, there's no need to do so — the caller already has access to the original Exception object (through the getCause() method of the thrown RuntimeException ) so the caller should decide whether to log it or not. 从设计的角度来看,没有必要这样做 - 调用者已经可以访问原始的Exception对象(通过抛出的RuntimeExceptiongetCause()方法),因此调用者应该决定是否记录它。

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

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