为什么需要自定义异常:
SUN没有定义好,所以我们根据自己业务来定义
怎么定义:
(1)定义一个受检查的异常(编译异常)继承于java.lang.Exception(2)定义一个运行时期的异常类(运行异常) 继承于
java.lang.RuntimeException
简单例子:
public class loginException extends RuntimeException{
private static final long serialVersionUID = 1L;
/**
* @param message 表示当前异常的原因/信息
* @param cause 表示造成异常的根本原因
*/
public loginException(String message, Throwable cause) {
super(message, cause);
}
public loginException(String message) {
super(message);
}
public loginException(Throwable cause) {
super(cause);
}
}
public class RegisterDemo {
//模拟数据库中已经存在的账号
private static String[] names= {"will","luck","lili"};
public static void main(String[] args) {
try {
//可能出现异常的代码
checkUsername("will");
}catch(loginException e) {
String errorMsg=e.getMessage();
System.out.println("给用户看:"+errorMsg);
}
}
//判断当前注册账号是否存在
public static boolean checkUsername(String username) {
for(String name:names) {
if(username.equals(name)) {
throw new loginException(name+"已经被使用了");
}
}
return true;
}
}