java异常什么时候抛出异常,java - 什么时候应该抛出IllegalArgumentException?

将IllegalArgumentException视为先决条件检查,并考虑设计原则:公共方法应该知道并公开记录其自身的前提条件。

我同意这个例子是正确的:

void setPercentage(int pct) {

if( pct < 0 || pct > 100) {

throw new IllegalArgumentException("bad percent");

}

}

If EmailUtil is opaque, meaning there's some reason the preconditions cannot be described to the end-user, then a checked exception is correct. The second version, corrected for this design:

import com.someoneelse.EmailUtil;

public void scanEmail(String emailStr, InputStream mime) throws ParseException {

EmailAddress parsedAddress = EmailUtil.parseAddress(emailStr);

}

If EmailUtil is transparent, for instance maybe it's a private method owned by the class under question, IllegalArgumentException is correct if and only if its preconditions can be described in the function documentation. This is a correct version as well:

/** @param String email An email with an address in the form abc@xyz.com

* with no nested comments, periods or other nonsense.

*/

public String scanEmail(String email)

if (!addressIsProperlyFormatted(email)) {

throw new IllegalArgumentException("invalid address");

}

return parseEmail(emailAddr);

}

private String parseEmail(String emailS) {

// Assumes email is valid

boolean parsesJustFine = true;

// Parse logic

if (!parsesJustFine) {

// As a private method it is an internal error if address is improperly

// formatted. This is an internal error to the class implementation.

throw new AssertError("Internal error");

}

}

这种设计可以采用两种方式。

If preconditions are expensive to describe, or if the class is intended to be used by clients who don't know whether their emails are valid, then use IllegalArgumentException. The top level method here is named scanEmail which hints the end user intends to send unstudied email through so this is likely correct.

If preconditions can be described in function documentation, and the class does not intent for invalid input and therefore programmer error is indicated, use IllegalArgumentException. Although not "checked" the "check" moves to the Javadoc documenting the function, which the client is expected to adhere to. IllegalArgumentException where the client can't tell their argument is illegal beforehand is wrong.

A note on IllegalStateException: This means "this object's internal state (private instance variables) is not able to perform this action." The end user cannot see private state so loosely speaking it takes precedence over IllegalArgumentException in the case where the client call has no way to know the object's state is inconsistent. I don't have a good explanation when it's preferred over checked exceptions, although things like initializing twice, or losing a database connection that isn't recovered, are examples.


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部