Java如何创建自定义Exception来限制HashMap的大小

0 java exception

我有一个方法可以将新项插入到a中HashMap,我希望在HashMap的大小大于特定值时限制HashMapby throw exception的大小,例如100,下面是我的实现:

public void addToHashMap(String id, Object value) throws HashMapOutOfBoundException{
    hashMap.put(id,value);    
}

private class HashMapOutOfBoundException extends Exception{
    //what should I do inside this class?
}
Run Code Online (Sandbox Code Playgroud)

Niz*_*ziL 5

为什么不简单:

public void addToHashMap(String id, Object value) {
    if (hashMap.size()+1 > MAX_SIZE)
      throw new HashMapOutOfBoundException();
    hashMap.put(id,value);    
}
Run Code Online (Sandbox Code Playgroud)

public class HashMapOutOfBoundException extends RuntimeException {}
Run Code Online (Sandbox Code Playgroud)

来自javadoc:

RuntimeException及其子类是未经检查的异常.如果方法或构造函数的throws子句可以通过执行方法或构造函数抛出并在方法或构造函数边界外传播,则不需要在方法或构造函数的throws子句中声明未经检查的异常.