程序在不使用 try and catch 时报告异常

Program reports exceptions when not using try and catch

我对 java 还是很陌生,我正在做一项关于密码学的学校作业。当我搜索从文件中读取的方法时,我看到很多方法都有一个 try 和 catch 块。我不太熟悉这些的使用,我想尝试避免在我的代码中使用它们,但是当我删除它们时,我在 new FileReader 中的新内容和 [=12 之后的括号中报告了两个异常=].但如果我确实使用它们,它的效果相对较好。谁能解释发生了什么?此外,当使用 catch 并尝试编码完成时,我得到一个异常 Null。感谢任何帮助。

import java.io.*;
import java.util.*;

public class Encrypter {

    public static void main(String[] args) {

        File input = null;
        if (1 < args.length) {
            input = new File(args[1]);
        } else {
            System.err.println("Invalid arguments count:" + args.length);
            System.exit(0);
        }
        String key = args[0];
        BufferedReader reader = null;
        try {
            int i = 0;
            String[] inputText = new String[20];
            String[] encryptText = new String[20];
            reader = new BufferedReader(new FileReader(input));
            while ((inputText[i] = reader.readLine()) != null) {
                encryptText[i] = inputText[i];
                System.out.println(inputText[i]);
                ++i;
            }
            int hash = key.hashCode();
            Random random = new Random(hash);
            String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ ";
            String alphabetPerm = alphabet;
            char temp;
            for (int j = 0; j < 100; j++) {
                int n1 = random.nextInt(27) + 0;
                int n2 = random.nextInt(27) + 0;
                char[] swapper = alphabet.toCharArray();
                temp = swapper[n1];
                swapper[n1] = swapper[n2];
                swapper[n2] = temp;
                String alphaSwap = new String(swapper);
                alphabet = alphaSwap;
            }
            System.out.println(alphabet);
            for (int k = 0; k < inputText.length; k++) {
                encryptText[k] = inputText[k].replaceAll("[^A-Za-z0-9 ]+", " ");
                for (int j = 0; j < inputText[k].length(); j++) {
                    int index = alphabetPerm.indexOf(encryptText[k].charAt(j));
                    encryptText[k] = alphabetSwapper(encryptText[k], alphabet, index, j);
                    System.out.println(encryptText[k]);
                }
            }
        } catch (Exception e) {
            System.err.println("Caught Exception: " + e.getMessage());
        }
    }

    public static String alphabetSwapper(String s, String alpha, int index, int value) {
        char toSwap = s.charAt(value);
        char[] inputChars = s.toCharArray();
        inputChars[value] = alpha.charAt(index);
        String swapped = new String(inputChars);
        return swapped;
    }
}

你最好不要像现在这样捕获异常,因为你正在丢弃两条最有用的信息,哪个异常被抛出以及它发生在哪里。

您可以将异常添加到 main()

throws 子句中,而不是捕获异常

例如

public static void main(String[] args) throws IOException {
    // ...
}

Can anyone explain what is happening?

当您阅读文件时,您可能是 IOException 例如如果文件不存在。您可能必须捕获此异常,但现在您可以让调用者 main 在它发生时将其打印出来。

Also when using the catch and try I get an exception Null when my encoding is done

这意味着您在没有消息的情况下触发异常。如果您打印异常及其发生的位置(或让 JVM 为您完成),您将看到位置。

为了确定发生这种情况的原因,我建议在调试器中单步执行代码,以便您了解每一行的作用。

您粘贴的表单的主要方法通常是程序的入口点,不会被其他 java 代码调用。因此,在离开程序之前捕获并处理所有异常是一种很好的做法。

'Handle' 可以表示不同的意思:

  1. 像您一样简单地将异常消息打印到控制台(在这种情况下,您会丢失信息,正如 Peter Lawrey 已经指出的那样)。
  2. 打印堆栈跟踪 (e.printStackStrace()),它在 stderr 输出上输出有关异常的更多信息。如果 main() 方法留下未捕获的异常,这就是 java 所做的。
  3. 如果使用记录器框架:记录器及其附加程序能够将所有异常信息打印到您选择的目的地。
  4. 处理它 (1-3) 并使用退出代码 != 0 退出 java,以便应用程序的(编程)调用者可以处理错误情况。

顺便说一句:我什至会抓住 Throwable。因此,您还捕获了可能的未经检查的异常(NullPointerException、ArrayIndexOutOfBoundsException 等)。并将尝试放在最开始(如果您在访问 args 数组时出错,您也会遇到 ArrayIndexOutOfBoundsException)

BTW2:如果你 not 在 main 方法中有任何 try..catch 我假设代码甚至不会编译,因为编译器可以检测到可能有未处理的检查异常(来自您的 IO 操作)。