简体   繁体   English

什么是异常错误,我该如何解决?

[英]What is a exception error and how do I fix it?

I am extremely new to Java and need your help. 我是Java的新手,需要您的帮助。 I was given the class MD5Digest by my instructor, and when I run the file by itself, it compiles without an issue. 我的讲师给我提供了MD5Digest类,当我自己运行文件时,它可以毫无问题地进行编译。 But when I copy and paste the class over to my file, it doesn't work. 但是,当我将类复制并粘贴到我的文件中时,它不起作用。 Can someone please help me? 有人可以帮帮我吗? I read that it has something to do with a try catch loop, but I am not sure how to set one up for this particular class, being that it was given to me and I don't know what half of it means. 我读到它与try catch循环有关,但是我不确定如何为该特定类设置一个,因为它是给我的,我不知道其中一半意味着什么。 Thanks in advance! 提前致谢!

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.security.MessageDigest;

public class Login{
    public static void main(String []args){
        Scanner user_input = new Scanner(System.in);

        String entered_username = Get_Credentials.get_username(user_input);
        String entered_password = Get_Credentials.get_password(user_input);
        MD5Digest.encrypt(entered_password);
        user_input.close();
        User[] all_users = File_Scanner.create_users();
    }
}

class Get_Credentials{
    public static String get_username(Scanner user_input){
        System.out.println("Username: ");
        return user_input.next();
    }

    public static String get_password(Scanner user_input){
        System.out.println("Password: ");
        return user_input.next();
    }

}

class File_Scanner{
    public static User[] create_users(){
        User users[] = new User[6];
        int index_counter = 0;

        try {
            File credentials_file = new File("credentials.txt");
            String pattern = "[^\"\\s]+|\"(\\\\.|[^\\\\\"])*\"";
            Scanner file_reader = new Scanner(credentials_file);

            while (file_reader.hasNextLine()) {
                users[index_counter] = new User();
                users[index_counter].username = file_reader.findInLine(pattern);
                users[index_counter].encrypted_password = file_reader.findInLine(pattern);
                users[index_counter].password = file_reader.findInLine(pattern);
                users[index_counter].role = file_reader.findInLine(pattern);
                file_reader.nextLine();
                index_counter++;
            }

            file_reader.close();
        }
        catch (Exception e) {
          System.out.println(e.getClass());
        }
        return users;
    }
}

class User {
    String username;
    String password;
    String encrypted_password;
    String role;
}

class MD5Digest {
    public static void encrypt(String original) throws Exception {
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(original.getBytes());
        byte[] digest = md.digest();
        StringBuffer sb = new StringBuffer();
        for (byte b : digest) {
            sb.append(String.format("%02x", b & 0xff));
        }

        System.out.println("original:" + original);
        System.out.println("digested:" + sb.toString());
    }

}

error thrown: 引发错误:

Login.java:12: error: unreported exception Exception; must be caught or declared to be thrown
        MD5Digest.encrypt(entered_password);
                         ^
1 error

What IDE are you using? 您正在使用什么IDE? You should be able to easily solve this error without needing any outside help. 您应该能够轻松解决此错误,而无需任何外部帮助。 On IntelliJ pressing Alt + Enter will give you the option to enclose the encrypt method call in a try/catch block, like such: 在IntelliJ上,按Alt + Enter将使您可以选择将加密方法调用包含在try / catch块中,例如:

    try {
        MD5Digest.encrypt(entered_password);
    } catch (Exception e) {
        e.printStackTrace();
    }

The method throws an exception, which basically means it can run into an error and the try catch block is a way to handle that error without your program crashing. 该方法引发异常,这基本上意味着它可能会遇到错误,而try catch块是一种处理该错误而不会导致程序崩溃的方法。

The encrypt method is located at the bottom, inside the MD5Digest class. 加密方法位于MD5Digest类内部的底部。 Looking at the first line: 看第一行:

public static void encrypt(String original) throws Exception

It's telling the compiler that it can possibly run into an Exception (error), and that you should be prepared to handle that possibility. 它告诉编译器它可能会遇到异常(错误),并且您应该准备应对这种可能性。 Hence the try/catch is required. 因此,需要try / catch。 It will try what's in the try brackets, and then if it runs into an error the code in the catch block will get executed. 它将尝试使用try括号中的内容,然后如果遇到错误,将执行catch块中的代码。

Change your main method to this: public static void main(String []args) throws Exception { . 将您的main方法更改为: public static void main(String []args) throws Exception {
Since you're calling the encrypt method though the main method, you also need to add the throws Exception to the main method as well. 由于您要通过main方法调用encrypt方法,因此还需要将throws Exception添加到main方法中。 Hope this helps! 希望这可以帮助!

Basically you just need to give a sign to your method about the possible exceptions, called checked exceptions in this case. 基本上,您只需要给方法加一个标记,说明可能的异常,在这种情况下称为检查异常。 So you use MessageDigest abstract class and the method that you access getInstance has a signature as throws NoSuchAlgorithmException . 因此,您使用MessageDigest抽象类,并且访问getInstance的方法具有throws NoSuchAlgorithmException的签名。 As @Dymas said, IDE can be helpful to see it more clearly. 正如@Dymas所说,IDE可以帮助您更清楚地看到它。

So as encrypt method uses getInstance method, you should let encript know about this checked exception. 因此,当encrypt方法使用getInstance方法时,您应该让encript知道此检查的异常。 Also since main calls encript , which brings the exception from the getInstance , you should also let the main know about this. 另外,由于main调用encript会带来getInstance的异常,因此您还应该让main知道这一点。 Which leads you to put: 这导致您提出:

public static void main(String []args) throws NoSuchAlgorithmException
public static void encrypt(String original) throws NoSuchAlgorithmException

This page also explains it quite well, it might be helpful for further read: 此页面也对此进行了很好的解释,可能有助于进一步阅读:

https://www.geeksforgeeks.org/checked-vs-unchecked-exceptions-in-java/ https://www.geeksforgeeks.org/checked-vs-unchecked-exceptions-in-java/

You can use signature of throws NoSuchAlgorithmException or as @K.Kretz says throws Exception , this is about the exception hierarchy which you could also have a look here with a picture: 您可以使用throws NoSuchAlgorithmException签名,也可以使用@ K.Kretz所说的throws Exception签名,这是关于异常层次结构的,您也可以在此处查看带有图片的图片:

https://itblackbelt.wordpress.com/2015/02/17/checked-vs-unchecked-exception-in-java-example/ https://itblackbelt.wordpress.com/2015/02/17/checked-vs-unchecked-exception-in-java-example/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 “错误:未报告的异常”是什么意思<XXX> ; 必须被抓住或被宣布被抛出”的意思,我该如何解决? - What does "error: unreported exception <XXX>; must be caught or declared to be thrown" mean and how do I fix it? 什么是挂起异常NullPointerException(帖子中出现完整错误),我该如何解决 - What is Suspended exception NullPointerException (Full error in post) and how do I fix it “error: '.class' expected”是什么意思,我该如何解决 - What does "error: '.class' expected" mean and how do I fix it 如何解决Java中的不匹配异常? - How do I fix a mismatch exception in Java? 如何修复空指针异常? - How do I fix Null Pointer Exception? 异常-空指针异常。 我如何解决它? - Exception - nullpointer exception. How do i fix it? 如何解决此运行时错误? 线程“主”中的异常java.lang.ArrayIndexOutOfBoundsException:-1 - How do i fix this runtime error? Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: -1 如何在此命令上修复此错误谢谢...线程“main”中的异常java.lang.ArrayIndexOutOfBoundsException:0 - How do I fix this error on this command thanks… Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 0 如何解决此错误? 线程“ main”中的异常java.lang.NoSuchMethodError:main - How do I fix this error? Exception in thread “main” java.lang.NoSuchMethodError: main 如何修复调用 Movie.toString() 错误时发生 Java 异常 - How do I fix a Java Exception occurred while calling Movie.toString() error
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM