learning target:
Goal: proficiently use the knowledge learned in Java
Subject content:
The content of this article: Implemented in Java: Implement a simple console version user login program, the program starts prompting the user to enter the user name and password. If the user name and password are wrong, use a custom exception method to deal with
Article Directory
Brief description + implementation code:
Although a wealth of exception classes have been built in Java, there may be some situations in our actual scenarios that require us to extend the exception classes to create exceptions that meet our actual situation.
For example: we implement a user login function
At this point, we may need to throw two exceptions when dealing with user name and password errors. We need to extend (inherit) the existing exceptions and create our business-related exception classes.
//密码错误异常类
public class PasswordError extends Exception {
public PasswordError(String message){
super(message);
}
}
//用户名错误异常类
public class UserError extends Exception{
public UserError(String message){
super(message);
}
}
import java.util.Scanner;
public class RegisterException {
private static String userName = "12345678";
private static String passerWord = "123456";
public static void main(String[] args) throws UserError, PasswordError {
Scanner sc = new Scanner(System.in);
System.out.print("请输入账号:");
String str1 = sc.nextLine();
System.out.print("请输入密码:");
String str2 = sc.nextLine();
login(str1, str2);
}
private static void login(String userName, String passerWord) throws PasswordError, UserError {
if (!RegisterException.userName.equals(userName)){
//判断用户名是否输入错误
throw new UserError("用户名错误");//抛出用户名错误异常
}
if (!RegisterException.passerWord.equals(passerWord)){
//判断密码是否输入错误
throw new PasswordError("密码错误");//抛出密码错误异常
}
System.out.println("登录成功");
}
}
operation result