一、常见异常
ClassCastException类型转换异常 ClassNotFoundException未找到相应类异常
ArithmeticException算术异常 ArrayIndexOutOfBoundsException数组下标越界异常
ArrayStoreException数组中包含不兼容的值抛出的异常
SQLException操作数据库异常类 NullPointerException空指针异常
NoSuchFieldException字段未找到异常 NoSuchMethodException方法未找到抛出的异常
NumberFormatException字符串转换为数字抛出的异常
FileNotFoundException文件未找到异常 IOException输入输出异常
二、自定义异常-----继承Exception即可-----步骤如下:
1.创建自定义异常类
2.在方法中通过throw关键字抛出异常对象
3.如果在当前抛出异常的方法中处理异常,可以使用try-catch语句块捕获并处理,否则在方法的声明处通过throws关键字抛出给方法调用者的异常
4.在出现异常方法的调用者中捕获并处理异常
如:public class UserException extends Exception {
public UserException() {
super();
}
public UserException(String message, Throwable cause,
boolean enableSuppression, boolean writableStackTrace) {
super();
}
public UserException(String message, Throwable cause) {
super(message, cause);
// TODO Auto-generated constructor stub
}
public UserException(String message) {
super(message);
// TODO Auto-generated constructor stub
}
public UserException(Throwable cause) {
super(cause);
// TODO Auto-generated constructor stub
}
}
调用:public void activeUser(String activeCode) throws UserException {
//根据激活码查找用户
try {
User user = ud.findUserByActiveCode(activeCode);
if(user!=null){
//激活用户
ud.activeCode(activeCode);
return;
}
throw new UserException("激活失败!");
} catch (SQLException e) {
e.printStackTrace();
throw new UserException("激活失败!");
}
}
捕获:UserService us = new UserService();
try {
us.activeUser(activeCode);
} catch (UserException e) {
e.printStackTrace();
//用户提示失败信息
response.getWriter().write(e.getMessage());
}