在Java(或任何其他具有已检查异常的语言)中,在创建自己的异常类时,如何确定是应该选中还是取消选中它?
我的直觉是,如果调用者能够以某种富有成效的方式恢复,那么将调用一个已检查的异常,其中未经检查的异常对于不可恢复的情况更多,但我会对其他人的想法感兴趣.
我注意到Integer.parseInt()你不必用try catch包围它,或者声明该方法可能抛出一个异常,尽管它"抛出"了一个NumberFormatException.
为什么我不必明确地捕获NumberFormatException或声明我的方法抛出它?
在Java中存在某些预定义的异常,如果抛出这些异常,则会报告发生了严重的事情,并且您可以更好地改进代码,而不是在catch块中捕获它们(如果我已正确理解它).但我仍然发现许多程序,其中包括以下内容:
} catch (IOException e) {
...
} catch (FileNotFoundException e) {
....
}
Run Code Online (Sandbox Code Playgroud)
我认为IOException和FileNotFoundException正是这种异常,我们不应该在catch块中捕获它们.为什么人们这样做?这样抓住他们会更好吗?无论如何,Java编译器都会警告这种问题.
谢谢.
我尝试编译下面但是在m16h(x)周围得到以下内容:
Line: 16
unreported exception java.lang.Exception; must be caught or declared to be thrown
Run Code Online (Sandbox Code Playgroud)
不知道为什么.我尝试了各种各样的东西,但似乎我做得对.
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class Test{
public static void main(String args[]){
byte[] k1 = parseHexString("eb35a6c92c3b8c98033d739969fcc1f5ee08549e", 20);
byte[] k2 = parseHexString("57cb8b13a1f654de21104c551c13d8820b4d6de3", 20);
byte[] k3 = parseHexString("c4c4df2f8ad3683677f9667d789f94c7cffb5f39", 20);
System.out.println(k1);
System.out.println(k2);
System.out.println(k3);
System.out.println(xor(m16h(add(xor(xor(m16h(add(k1, m16h(add(k2, m16h(k3))))), k3), k2), k1)), k3));
}
public static byte[] m16h(byte[] m) throws Exception {
return parseHexString(SHA1(m), 20);
}
private static byte[] xor(byte[] x, byte[] y) {
int l = x.length;
if …Run Code Online (Sandbox Code Playgroud) 谢谢你解决我的第一个问题,我现在收到一个新的错误
import java.io.*;
import javax.swing.*;
public class FileBrowser {
public static void main(String[] args) throws IOException {
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
File file = chooser.getSelectedFile();
String filename = file.getName();
System.out.println("You have selected: " + filename);
FileReader fr = new FileReader("filename");
BufferedReader br = new BufferedReader(fr);
String s;
while((s = br.readLine()) != null) {
System.out.println(s);
}
fr.close();
}
}
Run Code Online (Sandbox Code Playgroud)
错误:
java.io.FileNotFoundException: filename (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileInputStream.<init>(FileInputStream.java:97) …Run Code Online (Sandbox Code Playgroud)