And*_*zie 1 java exception-handling
我正在尝试制作一个cat克隆,并且我要求它在出现时接收输入-.
主要的(); 在这儿:
import java.io.*;
import java.util.*;
class cat {
public static void main(String[] args) {
for (int i = 0; i < args.length; i++) {
try{
filePrint(args[i]);
} catch(DashException letsTryThis){
catDash();
} catch(FileNotFoundException wrong) {
System.err.println(String.format("%s: File Not Found.", args[i]));
} catch (IOException noWords) {
System.err.println(String.format("%s: File can't be read.", args[i]));
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
filePrint()只是逐行打印文件并catDash()接收并打印标准输入.没什么特别的.
我要做的是有一个自定义异常,专门捕获-和调用catDash()(上面的第一个catch块).但是,无论如何,try/catch块总是抛出FileNotFound wrong异常(上面的第二个catch块).我的问题是,如何让它捕获特定原因并在第二个块之前抛出它?
我DashException定义它自己的文件:
import java.lang.Throwable;
public class DashException extends FileNotFoundException{
public DashException(Throwable cause){
super("-")
}
}
Run Code Online (Sandbox Code Playgroud)
您不会从任何地方抛出自定义异常.您需要throw在try块中自己的代码中使用它.例如:
if (args[i].equals("-")) {
throw new DashException();
}
Run Code Online (Sandbox Code Playgroud)
并且您可以th从构造中删除,因为此异常没有根本原因.