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"));
	}
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM