gpt4 book ai didi

java - 不使用try和catch时程序报异常

转载 作者:行者123 更新时间:2023-12-02 03:15:41 25 4
gpt4 key购买 nike

我对 Java 还很陌生,我正在做一项关于密码学的学校作业。当我寻找从文件中读取的方法时,我发现许多方法都有 try 和 catch block 。我对它们的使用不是很熟悉,我想尝试避免在我的代码中使用它们,但是当我删除它们时,我在 new FileReader 中的 new 和括号中报告了两个异常在reader.readLine()之后。但如果我确实使用它们,效果会相对较好。谁能解释发生了什么?另外,当使用 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 - 不使用try和catch时程序报异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40349269/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com