如何避免重复复杂的catch块

mxc*_*xcl 18 java

我有这个代码:

try {
    do_stuff();
    return do_more_stuff();
} catch (UnsupportedEncodingException e) {
    throw CustomException.programmer_error(e);
} catch (ProtocolException e) {
    throw CustomException.programmer_error(e);
} catch (MalformedURLException e) {
    throw CustomException.programmer_error(e);
} catch (SocketTimeoutException e) {
    throw new CustomException(e);
} catch (IOException e) {
    throw CustomException.unexpected_error(e);
}
Run Code Online (Sandbox Code Playgroud)

我现在需要在另一个类似的函数中拥有所有这些catch块.避免重复的最佳方法是什么?

请注意,两个try块内的代码不是很相似.

另外,我无法真正把这些捕获量提升到更高的水平.

请注意,我宁愿避免:

try {
    do_stuff();
    return do_more_stuff();
} catch (Exception e) {
    handle_exception_via_rtti(e);
}
Run Code Online (Sandbox Code Playgroud)

p.m*_*ino 7

我个人试着去做

do_stuff();
return do_more_stuff();
Run Code Online (Sandbox Code Playgroud)

部分符合更一般的格式以应用策略(作为模式).

然后你可以重构你调用这种块的所有地方,这样他们就可以调用一个更通用的块(捕获只被布置一次).

  • 确实,战略模式将在这里发挥作用.对于后代,这将涉及替换`do_stuff(); 使用`return strategy.do_stuff()返回do_more_stuff()`.因此,您将策略传递给异常处理函数.这种模式需要所有策略从do_stuff()返回相同的类型; (2认同)

Bal*_*usC 5

请注意,我宁愿避免:

然后要么只是忍受它,要么等到JDK7附带Multicatch,这样你就可以重写:

try {
    do_stuff();
    return do_more_stuff();
} catch (UnsupportedEncodingException | ProtocolException | MalformedURLException e) {
    throw CustomException.programmer_error(e);
} catch (SocketTimeoutException e) {
    throw new CustomException(e);
} catch (IOException e) {
    throw CustomException.unexpected_error(e);
}
Run Code Online (Sandbox Code Playgroud)

您也可以将其移动到构造函数中CustomException并执行(讨厌的)全局捕获,但是您需要添加一堆(讨厌的)if/else块来确定异常原因的类型.总而言之,我只是喜欢坚持你已经做过的方式.

更新:另一种方法是拆分/重构行,这些行可能会将异常作为单独的任务抛出到另一个方法块中CustomException.例如

try {
    do_stuff_with_encoding();
    do_stuff_with_url();
    do_stuff_with_ws();
    // ...
    return do_more_stuff();
} catch (SocketTimeoutException e) {
    throw new CustomException(e);
} catch (IOException e) {
    throw CustomException.unexpected_error(e);
}

...

public SomeObject do_stuff_with_encoding() throws CustomException {
    try {
        do_stuff();
    } catch (UnsupportedEncodingException e) {
        throw CustomException.programmer_error(e);
    }
}  

public SomeObject do_stuff_with_url() throws CustomException {
    try {
        do_stuff();
    } catch (MalformedURLException e) {
        throw CustomException.programmer_error(e);
    }
}  

public SomeObject do_stuff_with_ws() throws CustomException {
    try {
        do_stuff();
    } catch (ProtocolException e) {
        throw CustomException.programmer_error(e);
    }
}  
Run Code Online (Sandbox Code Playgroud)