java - Try-Catch 的 Catch 部分未执行

标签 java exception try-catch

我正在编写一个用于学习目的的短代码,要求用户输入密码才能登录 Facebook。我正在测试异常处理,由于某种原因,当密码错误时,Catch 部分没有执行。代码是:

import java.util.Scanner;

public class FacebookLogin {
    
    
    public static void printPassword() {
        Scanner sc = new Scanner(System.in);
        String password;
        
        try {
            
            System.out.print("Enter your password : ");
            password = sc.next();
        
        } catch (Exception x) {
            do {            
            System.out.println("Your password is incorrect. Try again!");
            System.out.print("Enter your password : ");
            sc.nextLine();
            password = sc.next();
            
            
            } while (password != "password");
        }
        sc.close();
        
    }
    
    public static void main(String[] args) {
        
        
        System.out.println("Welcome to Facebook!");
        
        printPassword();
        
        System.out.println("Congratulations, you have logged in to Facebook!");
        
        
    }
    
}

上述脚本的几次运行:

Welcome to Facebook!

Enter your password : ksskasjaks

Congratulations, you have logged in to Facebook!

另一次运行:

Welcome to Facebook!

Enter your password : password

Congratulations, you have logged in to Facebook!

我排除了这样的情况,当然这里唯一的密码是“password”:

Welcome to Facebook!

Enter your password : ksskasjaks

Your password is incorrect. Try again!

Enter your password : password

Congratulations, you have logged in to Facebook!

知道为什么它没有按预期工作吗?谢谢。

最佳答案

使用 try catch:

 public static void enterPassword() throws Exception {
    Scanner sc = new Scanner(System.in);
    String password;
    System.out.print("Enter your password : ");
    password = sc.next();
    if (!password.equals("password")) {
        throw new Exception();
    }
}

public static void printPassword() {
    try {
        enterPassword();
    } catch (Exception e) {
        System.out.println("Your password is incorrect. Try again!");
        printPassword();
    }
}

public static void main(String[] args) {


    System.out.println("Welcome to Facebook!");

    printPassword();

    System.out.println("Congratulations, you have logged in to Facebook!");


}

关于java - Try-Catch 的 Catch 部分未执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57021988/

相关文章:

Java 泛型 - 不在界限之内

java - 如何在 JSF 模板中定义将在别处定义的 onLoad 函数

exception - Kotlin 删除检查异常背后的想法是什么?

c++ - 为什么不捕获 `std::promise::~promise` 中已经传播的异常

scala - 创作 future 与尝试

vb.net - VB.net 中的 Err.Number 与 try-catch

javascript - Node.js MySQL 查询中的 Try/Catch 是冗余的吗?

java - maven 忽略 pom.xml 中的源级别

javascript - JavaScript try-catch 是否忽略了预期的偶然错误的不良做法?

java - 静态对象(例如单例)会泄漏非静态上下文吗?为什么?