Java,类特定异常与标准异常 [英] Java, Class-specific Exceptions vs. Standard Exceptions

查看:146
本文介绍了Java,类特定异常与标准异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经更新了一个现有的库来抛出异常,以帮助改进使用库的人员调试。

I've been updating an existing library to throw exceptions to help improve debugging by people using the library.

起初我以为我会定义异常然而,事实证明,大多数异常只是现有运行时异常的扩展(例如, FooNegativeIntArgumentException extends IllegalArgumentException FooNullBarException extends NullPointerException )具有特定的消息。

At first, I thought I'd define exceptions specific to each class, however it turns out most of those exceptions are simply extensions of existing runtime exceptions (e.g., FooNegativeIntArgumentException extends IllegalArgumentException, FooNullBarException extends NullPointerException) with specific messages.

定义新异常与使用现有异常有什么权衡?有没有约定/最佳做法?

What are the trade-offs of defining new exceptions vs. using existing ones? Are there any conventions/best-practices?

另外,鉴于需要向后兼容性,大多数(如果不是全部)这些异常都是运行时异常。

Also, given the need for backwards compatibility, most (if not all) of these exceptions are runtime exceptions.

推荐答案

这是我采取为什么我们有不同类型的异常和何时创建自定义异常类型(注意:这使用.NET类型作为示例,但相同的原则适用于Java和任何其他使用结构化错误处理的语言)。发布这个完整的答案可能太长了,所以我只是发布两个关键的提取。

Here's my take on why we have different types of exception and when to create custom exception types (note: this uses .NET types as examples but the same principles apply to Java and any other language that uses structured error handling). It's probably too long to post here as a complete answer so I'll just post the two key extracts.



  1. 何时抛出不同类型的异常?对于可以以不同程序方式处理的每个症状,抛出不同类型的异常。

  1. When to throw different types of exception? Throw a different type of exception for each symptom that can be programmatically handled differently.

何时创建自定义异常类型?当您需要使用附加信息注释异常以帮助对症状进行编程处理时,创建自定义异常类型。

When to create custom exception types? Create a custom exception type when you need to annotate the exception with additional information to aid in the programmatic handling of the symptom.


在您的情况下,听起来不像您的自定义异常类型填补了使用标准异常可以传达的症状的差距,并且它们没有为编程处理添加任何其他信息,所以不要创建它们。只需使用标准的。

In your case it doesn't sound like your custom exception types are filling a gap in the symptoms that can be conveyed using standard exceptions, and they aren't adding any additional information for programmatic handling, so don't create them. Just use standard ones instead.

这篇关于Java,类特定异常与标准异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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