异常处理策略 - 重用异常代码 [英] Exception handling strategy - reuse exception codes

查看:205
本文介绍了异常处理策略 - 重用异常代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个这样的过程的应用程序。

I'm working on an application where the process goes on like this

UI --> backend process --> result to UI.

在我的Java代码中,我使用try-catch处理了我的异常,但是在我有所以很多重复的异常可能会在不同的类中引发同样的异常,从而降低了可读性和代码的重用。

In my Java code, I have handled my exceptions using try-catch, But in the code I have so many repeated exceptions that may throw same exceptions in different classes, which reduces the readability and code reuse.

所以,我打算做一个异常处理策略,在不同的类中抛出相同的异常,我需要组织异常并重新使用异常代码。

So, I am planning to do a exception handling strategy so that instead of throwing the same exception in different classes, I need to organize the exception and reuse the exception codes.

有没有人可以建议我最好的异常处理技术来做到这一点? p>

Could anyone suggest me best exception handling technique to do this?

推荐答案

始终句柄未选中的异常尽可能接近源,但避免创建它们,一个href =http://www.spamer.me.uk/wiki/doku.php/oo_java_checked_vs_unchecked =nofollow>本来不安全的编程习语的最后手段;当程序不可能恢复时。

Always handle Unchecked Exceptions as close to their source as possible but avoid creating them, they are an inherently unsafe programming idiom of last resort; when there is no possibility that the program can recover.

在实施应用程序时,代码防御性地在编码时始终使用检查异常来管理异常工作流;例如当您的代码无法兑现其界面时,合同

When implementing application, code defensively buy always using checked exceptions when coding to manage exceptional work flows; such as when your code fails to honour its interface "Contract".

应用程序不应该因为无法访问第三方信用评分系统而导致未经检查的异常崩溃。禁用该选项并继续允许创建现金客户。

An application should not crash with an unchecked exception because it cannot reach a third party credit score system. Disable that option and continue allowing Cash Customers to be created.

概括异常处理,但专门制作他们的创建。例如

Generalise exception handling but specialise their creation. e.g.

CustomerNotFound extends CustomerException
CreditCustomerNotFound  extends CustomerException 
CashCustomerNotFound  extends CutomerException

{
   aCustomer = customerList.find( ... )
} catch CustomerNotFound() { 
   logger.warn( ... )
   throw CustomerException(CustomerNotFound)
}

InvoiceAddressException extends InvoiceException

执行更接近源的特定处理可能的,记录细节和尽可能的清理。仅传播

Do specific handling as close to the source as possible, log details and clean up as much as possible. Propagate only

根据实际情况,将一般处理和报告设置为接近用户界面。

Do general handling and reporting as close to the user interface as is realistic.

这篇关于异常处理策略 - 重用异常代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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