如何避免重复复杂的catch块 [英] How to avoid duplicating complicated catch blocks

查看:146
本文介绍了如何避免重复复杂的catch块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码:

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);
}

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

I now need to have all those catch blocks in another similar function. What is the best way to avoid duplication here?

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

Note that the code inside the two try blocks is not very similar.

此外,我无法真正把这些捕获量提高。

Also I can't really put the set of catches higher up.

注意,我宁愿避免:

try {
    do_stuff();
    return do_more_stuff();
} catch (Exception e) {
    handle_exception_via_rtti(e);
}


推荐答案

我个人试着制作

do_stuff();
return do_more_stuff();

部分符合更通用的格式以应用策略(作为模式)。

part conform to a more general format in order to apply Strategy (as a pattern).

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

Then you can refactor all the places where you call this kind of block so that they can call a more generalized block (where the catches are laid out just once).

这篇关于如何避免重复复杂的catch块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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