创建UserDeletedException.java文件,内容为:
/**
*
*/
package com.test.my;
/**
* @author 苏显斌
*
*/
public class UserDeletedException extends Exception {
private static final long serialVersionUID = -4170867320856684404L;
public UserDeletedException() {
super("用户已经被删除!");
}
public UserDeletedException(String msg) {
super(msg);
}
public String toString() {
return super.toString();
}
}
创建UserNotFoundException.java文件,内容为:
/**
*
*/
package com.test.my;
/**
* @author 苏显斌
*
*/
public class UserNotFoundException extends Exception {
private static final long serialVersionUID = 125267836539588415L;
public UserNotFoundException() {
super("无法找到用户!");
}
public UserNotFoundException(String msg) {
super(msg);
}
public String toString() {
return super.toString();
}
}
创建testc.java文件,内容为:
package com.test.my;
public class testc {
/**
* @param args
*/
public static void main(String[] args) {
try {
catchException(7);
} catch (UserDeletedException delEx) {
System.out.println(delEx.toString());
System.out.println("捕获了用户被删除异常!");
} catch (UserNotFoundException notFoundEx) {
System.out.println(notFoundEx.toString());
System.out.println("捕获了用户不存在异常!");
} catch (Exception e) {
System.out.println(e.toString());
System.out.println("捕获了未知的异常!");
}
}
public static void catchException(int number) throws Exception {
if (number > 5)
throw new UserDeletedException();
else if (number < -5)
throw new UserNotFoundException();
else
throw new Exception("未知的异常!");
}
}