实际场景中,一些情况需要我们对异常类进行扩展,创建符合实际情况的异常,比如实现用户登录功能时,当出现用户名和密码错误时,需要我们自己抛出异常。
// public static void login(String username, String password){
// if(!TestDemo.username.equals(username)){
// //处理用户名错误
// }
// if(!TestDemo.password.equals(password)){
// //处理错误密码
// }
// System.out.println("登录成功!");
// }
//
// public static void main(String[] args) {
// login("admin","123456");
// }
/*
自定义异常类
当我们处理用户名以及密码错误时需要抛出两种异常,我们可以基于已有的异常类进行扩展或者说继承,主动创建业务相关的类
*/
class UserError extends Exception {
public UserError(String message) {
super(message);
}
}
class PasswordError extends Exception {
public PasswordError(String message) {
super(message);
}
}
public class TestDemo {
private static String username = "admin";
private static String password = "123456";
public void login(String userName, String passWord) throws UserError, PasswordError{
if(!TestDemo.username.equals(userName)){
throw new UserError("用户名错误!");
}
if(!TestDemo.password.equals(passWord)){
throw new PasswordError("密码错误!");
}
System.out.println("登录成功!");
}
//这时我们可以将login改成如下形式:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNextLine()){
String name = sc.nextLine();
String num = sc.nextLine();
try {
TestDemo test = new TestDemo();
test.login(name, num);
} catch (UserError userError) {
userError.printStackTrace();
} catch (PasswordError passwordError) {
passwordError.printStackTrace();
}
}
}
}
此外需要注意的是:
1.自定义异常类通常继承Exception或者RuntimeException
2.继承Exception的异常默认为受查异常
2.继承RuntimeException的异常默认为非受查异常