何时应该抛出IllegalArgumentException? [英] When should an IllegalArgumentException be thrown?

查看:867
本文介绍了何时应该抛出IllegalArgumentException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我担心这是一个运行时异常,所以应该谨慎使用。

标准用例:

  void setPercentage(int pct){
if(pct< 0 || pct> 100){
throw new IllegalArgumentException(bad percent);
}
}

但这似乎会强制以下设计:

  public void computeScore()throws MyPackageException {
try {
setPercentage(userInputPercent);
}
catch(IllegalArgumentException exc){
throw new MyPackageException(exc);
}
}

将其恢复为检查异常。 / p>

好的,但是让我们一起去吧。如果输入不正确,您将收到运行时错误。所以首先这实际上是一个相当困难的策略来统一实现,因为你可能需要做相反的转换:

  public void scanEmail (String emailStr,InputStream mime){
try {
EmailAddress parsedAddress = EmailUtil.parse(emailStr);
}
catch(ParseException exc){
throw new IllegalArgumentException(bad email,exc);
}
}

更糟糕的是 - 检查 0< = pct&&& pct <= 100 可以预期客户端代码静态地执行,对于诸如电子邮件地址之类的更高级数据,或者更糟糕的是,必须对数据库进行检查,因此不是这样一般客户端代码无法预先验证。



所以基本上我所说的是没有看到有意义的一致的政策来使用抛出:IllegalArgumentException 。它似乎不应该被使用,我们应该坚持我们自己检查的例外。这是一个很好的用例来引发这个问题?

解决方案

IllegalArgumentException的api文件是:



抛出表示一种方法已被传递非法或不正确的参数。



从查看如何在jdk库中使用它,我会说:




  • 这似乎是一个防御措施抱怨明显不好的输入,输入之前可以进入作品,并导致一些失败的中途通过一个无意义的错误消息。


  • 它用于抛出一个被检查的异常(尽管它在java.lang.reflect代码中出现了,但是对于抛出异常抛出的可疑级别的关注也不是很明显),这太麻烦了。




我将使用IllegalArgumentException对通用实用程序进行最后一次防御性参数检查(试图与jdk使用保持一致),其中期望是一个不好的参数是一个程序员的错误,类似于NPE。我不会用它来在业务代码中实现验证。我当然不会将其用于电子邮件示例。


I'm worried that this is a runtime exception so it should probably be used sparingly.
Standard use case:

void setPercentage(int pct) {
    if( pct < 0 || pct > 100) {
         throw new IllegalArgumentException("bad percent");
     }
}

But that seems like it would force the following design:

public void computeScore() throws MyPackageException {
      try {
          setPercentage(userInputPercent);
      }
      catch(IllegalArgumentException exc){
           throw new MyPackageException(exc);
      }
 }

To get it back to being a checked exception.

Okay, but let's go with that. If you give bad input, you get a runtime error. So firstly that's actually a fairly difficult policy to implement uniformly, because you could have to do the very opposite conversion:

public void scanEmail(String emailStr, InputStream mime) {
    try {
        EmailAddress parsedAddress = EmailUtil.parse(emailStr);
    }
    catch(ParseException exc){
        throw new IllegalArgumentException("bad email", exc);
    }
}

And worse - while checking 0 <= pct && pct <= 100 the client code could be expected to do statically, this is not so for more advanced data such as an email address, or worse, something that has to be checked against a database, therefore in general client code cannot pre-validate.

So basically what I'm saying is I don't see a meaningful consistent policy for the use of IllegalArgumentException. It seems it should not be used and we should stick to our own checked exceptions. What is a good use case to throw this?

解决方案

The api doc for IllegalArgumentException is:

Thrown to indicate that a method has been passed an illegal or inappropriate argument.

From looking at how it is used in the jdk libraries, I would say:

  • It seems like a defensive measure to complain about obviously bad input before the input can get into the works and cause something to fail halfway through with a nonsensical error message.

  • It's used for cases where it would be too annoying to throw a checked exception (although it makes an appearance in the java.lang.reflect code, where concern about ridiculous levels of checked-exception-throwing is not otherwise apparent).

I would use IllegalArgumentException to do last-ditch defensive argument-checking for common utilities (trying to stay consistent with the jdk usage), where the expectation is that a bad argument is a programmer error, similar to an NPE. I wouldn't use it to implement validation in business code. I certainly wouldn't use it for the email example.

这篇关于何时应该抛出IllegalArgumentException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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