java.lang.IllegalArgumentException的使用场景
抛出这个异常说明方法传入一个非法的或者不合适的参数。 举个例子:getUser(int username)方法,不允许传入空字符串或者null。但是有个调用的方法,没做检查,传入了null或者空字符串,这时候getUser方法就应该要抛出IllegalArgumentException告诉调用者:hi!这个参数不能为empty或者null。 java.lang.IllegalArgumentException继承至RuntimeException,所以它是一个unchecked异常,它不需要在方法里加throws
声明!
如果在系统中出现这个异常,你唯一要做的就是检查传入的参数是否合法!所有的unchecked异常必须要用log记录下来的,所以exception message必须要描述的清楚--具体是哪个参数出错了。
下面的例子:
扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄
SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。
import java.io.File;
public class IllegalArgumentExceptionExample {
/**
*
* @param parent, The path of the parent node.
* @param filename, The filename of the current node.
* @return The relative path to the current node, starting from the parent node.
*/
public static String createRelativePath(String parent, String filename) {
if(parent == null)
throw new IllegalArgumentException("The parent path cannot be null!");
if(filename == null)
throw new IllegalArgumentException("The filename cannot be null!");
return parent + File.separator + filename;
}
public static void main(String[] args) {
// The following command will be successfully executed.
System.out.println(IllegalArgumentExceptionExample.createRelativePath("dir1", "file1"));
System.out.println();
// The following command throws an IllegalArgumentException.
System.out.println(IllegalArgumentExceptionExample.createRelativePath(null, "file1"));
}
}
更多精彩

