java.lang.IllegalArgumentException的使用场景

抛出这个异常说明方法传入一个非法的或者不合适的参数。
举个例子:getUser(int username)方法,不允许传入空字符串或者null。但是有个调用的方法,没做检查,传入了null或者空字符串,这时候getUser方法就应该要抛出IllegalArgumentException告诉调用者:hi!这个参数不能为empty或者null。
java.lang.IllegalArgumentException继承至RuntimeException,所以它是一个unchecked异常,它不需要在方法里加throws声明!
 
如果在系统中出现这个异常,你唯一要做的就是检查传入的参数是否合法!所有的unchecked异常必须要用log记录下来的,所以exception message必须要描述的清楚--具体是哪个参数出错了。
 
下面的例子:
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"));
	}
}

 

posted @ 2019-04-08 11:57  八球  阅读(30074)  评论(0编辑  收藏  举报