我对 Java 中的异常以及何时使用哪种特定的实现方式感到有些困惑。
我以 IllegalArgumentException 为例,但我想解决的主要问题是何时抛出、扩展或抛出新异常?
另外,我还有一个任务,我必须创建一个 java 类,并且规范模糊地指出构造函数应该抛出一个 IllegalArgumentException 那么哪个是最好的使用?
public class Test{
//when does one use this type of exception
public Test(String yourName) throws IllegalArgumentException{
//code implemented
}
//when does one use this type of exception
public Test(String yourName) extends IllegalArgumentException{
//code implemented
}
public Test(String yourName){
if(yourName.length() <= 0){
//why not use this type of exception instead
//and what happens when I use this type of exception
throw new IllegalArgumentException("Please Enter Your Name..!");
}
}
}
提前致谢。