为什么我的程序不接受自定义异常?

时间:2016-07-04 14:04:44

标签: 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]));
      }
    }
  }
}

filePrint()只是逐行打印文件,catDash()接收并打印stdin。没什么特别的。

我要做的是有一个自定义异常,专门捕获-并调用catDash()(上面的第一个catch块)。但是,无论如何,try / catch块总是抛出FileNotFound wrong异常(上面的第二个catch块)。我的问题是,如何让它捕获特定原因并在第二个块之前抛出它?

我的DashException定义了它自己的文件:

import java.lang.Throwable;

public class DashException extends FileNotFoundException{
  public DashException(Throwable cause){
    super("-")
  }
}

1 个答案:

答案 0 :(得分:9)

您不会从任何地方抛出自定义异常。您需要在throw块中自己的代码中try。 E.g:

if (args[i].equals("-")) {
     throw new DashException();
}

您可以从构造函数中删除th,因为此异常没有根本原因。