Java中的子类化异常:何时不是自定义消息“足够好”? [英] Subclassing Exception in Java: when isn't a custom message "good enough"?

查看:111
本文介绍了Java中的子类化异常:何时不是自定义消息“足够好”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是最佳实践问题。

我目前正在使用旧的Java代码。我看到很多Exception的子类只覆盖了构造函数。我不确定是否有任何像这样的子类化Exception的实际用法。我认为只是调用Exception构造函数并传入消息同样有效,并且不会有很多子类。代码是责任。

I'm working with old Java code at the moment. I'm seeing a lot of subclasses of Exception only overwrite the constructors. I'm not sure if there is any practical use of subclassing Exception like this. I think just calling the Exception constructor and pass in a message would be just as effective, and there wouldn't be many subclasses around. Code is liability.

推荐答案

子类化的重点是你的代码可以区分不同类型的失败并区别对待他们。如果您只是更改消息,那么 human 可以在日志中区分它们,但这就是全部。

The point of subclassing is that your code can distinguish different types of failure and treat them differently. If you just change the message, then a human can distinguish them in the logs, but that's all.

如果您看到的异常是并没有实际处理不同,但只是陷入了一个全能的 catch(例外e)然后可能有人对子类过度热情,但它通常对干净利用很有用分离代码层并确定哪些类应该处理哪种类型的问题。

If the exceptions you are seeing are not actually handled differently, but just caught in a catch-all catch(Exception e) then perhaps someone was being over-enthusiastic with the subclasses, but it is often useful for cleanly separating layers of code and working out which classes should handle which kinds of problem.

例如,一种类型的异常可能表示超时,并且可能适合重试在短暂的延迟之后,而另一种类型的异常表示不可恢复的故障(可能是无效的查询),必须将其抛出到更高的级别或者可能向用户指示。

For example, one type of exception may indicate a timeout, and it may be appropriate to retry after a short delay, whereas another type of exception indicates an unrecoverable failure (an invalid query, perhaps) which must be thrown up to a higher level or perhaps indicated to the user.

这篇关于Java中的子类化异常:何时不是自定义消息“足够好”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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