自定义异常(例如 IllegalArgumentException)以获得良好的日志信息
当方法可以获得空引用而不是有效对象值时,拥有像 IllegalArgumentException 这样的自定义异常并在所有情况下抛出它是个好主意吗?
public void method(String str){
if(str == null)throw new CustomIllegalArgumentException("str cannot be null");
}
我认为这样我总能看到这种非法参数异常和其他运行时异常之间的区别。
这是好主意还是坏主意?
PS:我看过这样的帖子 避免 != null 语句
**更新:**所以我会知道这是程序员故意的异常,我会有清晰的日志。
Does it good idea to have custom exception like IllegalArgumentException and throw it in all cases when methods can get null reference instead of valid object value?
public void method(String str){
if(str == null)throw new CustomIllegalArgumentException("str cannot be null");
}
I think that such way I can always see difference between such illegal argument exceptions and other RuntimeExceptions.
Does it good idea or not?
P.S.: I looked at such posts like
Avoiding != null statements
**UPDATE:**So I will know that is programmer-intended exception and I will have clear log.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
IllegalArgumentException
是标准异常,而不是自定义异常。当参数为null
时,通常会抛出NullPointerException
,而实际上本不应该是这样。一般来说,当标准例外适合您的特殊情况时,您应该更喜欢它们。另请参阅“Effective Java 第 2 版”中的第 60 条(“支持使用标准异常”)。这样做的优点之一是,您可以为您自己的代码和您使用的库中可能发生的类似情况编写一个处理程序。
为了区分异常,应该使用它们携带的字符串消息。此外,堆栈跟踪将指示异常是从您自己的代码还是从其他代码引发的。不需要额外的异常类。
创建自己的异常类可能是合理的一种情况是,您需要异常携带有关它所指示的异常情况的额外信息。在这种情况下,您仍然应该从适当的标准类派生异常,以便可以编写一个处理程序来处理来自您自己的代码和您使用的库的类似条件的异常。
另请参阅
先决条件
来自 google 的实用程序类。特别是< code>checkNotNull() 实用程序方法,当其参数为null
时,也会抛出NullPointerException
。IllegalArgumentException
is a standard, not a custom exception. It is conventional to throwNullPointerException
when argument isnull
when it shouldn't be.You should in general prefer standard exceptions when they are suitable to your special case. See also item 60 in "Effective Java 2nd edition" ("Favor the use of standard exceptions"). One advantage of this is that you can write a single handler for similar conditions which may occur both in your own code and in libraries you use.
In order to differentiate the exceptions, you should use the string message they carry. Also, the stack trace will indicate whether the exception has been thrown from your own code or from other code. No need for extra exception class.
One case when it may be reasonable to create your own exception class is when you need the exception to carry extra information about the exceptional condition it indicates. In this case you should still derive the exception from the appropriate standard class, so that a single handler can be written that handles exceptions for similar conditions coming from both your own code and libraries you use.
See also
Preconditons
utility class from google. In particularcheckNotNull()
utility method which also throwsNullPointerException
when its argument isnull
.