首页 > 编程语言 > 详细

java.lang.IllegalArgumentException的使用场景

时间:2019-04-08 12:51:48      阅读:136      评论:0      收藏:0      [点我收藏+]
抛出这个异常说明方法传入一个非法的或者不合适的参数。
举个例子: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"));
	}
}

 

java.lang.IllegalArgumentException的使用场景

原文:https://www.cnblogs.com/8qiu/p/10669684.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!