抛出异常时的Java最佳实践:抛出核心Java异常 [英] Java best practices when throwing exceptions: throwing core Java exceptions

查看:101
本文介绍了抛出异常时的Java最佳实践:抛出核心Java异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

与其抛出 new Exception(某些消息,也许是某些原因),这意味着我方法的所有调用者都需要捕获Exception(其中可能包括RuntimeExceptions),发生问题时,我想抛出一种更具体的异常类型。

Instead of throwing new Exception("Some message", maybeSomeCause), which means that all callers of my method will need to catch Exception (which can include RuntimeExceptions), I'd like to throw a more specific type of exception when a problem occurs.

我可以创建自己的扩展异常类型或其他异常类型的异常类型,但是我是好奇是否可以重用Java核心语言附带的一些异常,例如:

I can create my own exception types which extend Exception or another exception type, but I am curious if it is a good idea to re-use some exceptions that come with core Java language, such as:


  • IllegalArgumentException

  • UnsupportedOperationException

  • IOException

  • 其他?

  • IllegalArgumentException
  • UnsupportedOperationException
  • IOException
  • Others?

还有其他我想念的人吗?我在这里找到了核心例外的基本列表: http://rymden.nu/exceptions.html

Are there others that I am missing? I found a basic list of the 'core' exceptions here: http://rymden.nu/exceptions.html, with humous explanations.

谢谢!

编辑:

核心例外列表是否完整?

Is there a good list of 'core' exceptions?

到目前为止的列表:

  • http://rymden.nu/exceptions.html
  • Java 7 Exception class API

推荐答案

是,这样做非常好。实际上,它甚至是用 Effective Java,第二版编写的。参见第248页上的第60条:优先使用标准异常

Yes, it's very good to do that. In fact, it's even written about in Effective Java, 2nd ed. See item 60 on page 248: "Favor the use of standard exceptions"


重用预先存在的异常有几个好处。在这些
中,最主要的是,它使您的API更易于学习和使用,因为它与程序员已经熟悉的
建立的约定相匹配。紧随其后的是
,这是因为使用API​​的程序更容易阅读
,因为它们不会因陌生的异常而混乱。最后(最少
),较少的异常类意味着较小的内存占用量和
的加载时间减少了。

Reusing preexisting exceptions has several benefits. Chief among these, it makes your API easier to learn and use because it matches established conventions with which programmers are already familiar. A close second is that programs using your API are easier to read because they aren’t cluttered with unfamiliar exceptions. Last (and least), fewer exception classes mean a smaller memory footprint and less time spent loading classes.

这篇关于抛出异常时的Java最佳实践:抛出核心Java异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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