2016-07-04 39 views
1

我正在尝试制作一个cat克隆,并且我要求它在接收到-时接收输入。为什么我的程序不接受自定义异常?

main();是在这里:

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()接收并打印标准输入。没什么特别的。

我想要做的是有一个自定义异常,专门捕获-并呼吁catDash()(上面的第一个catch块)。但是,无论如何,try/catch块总是抛出异常(上面的第二个catch块)。我的问题是,我如何才能在第二块之前抓住一个特定的原因并把它扔出去呢?

DashException定义它自己的文件:

import java.lang.Throwable; 

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

DashException是一个FileNotFoundException ...为什么你不只是抛出一个FileNotFoundException ??? –

回答

9

你不会从任何地方把你的自定义异常。您需要throw它在try区块中的代码中。例如: -

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

而且你可以从constuctor删除th,因为没有根源此异常。

+0

filePrint()抛出FileNotFoundException,IOException和我的自定义DashException。你是这个意思吗? –

+0

您不需要将其添加到签名中,因为'DashException'是一个'FileNotFoundException'。 – meskobalazs

+0

只要将你的异常添加到抛出声明中,如果它不像@meskobalazs显示的那样抛出异常,就不会对你的特定异常没有好处。 –

相关问题