简体   繁体   English

Java尝试捕获错误

[英]Java try and catch error

I am trying to try and catch an error in my method to write the contents of change drawer to a html document. 我试图在我的方法中捕获错误,将更改抽屉的内容写入html文档。 The error, java.io.FileNotFoundException, appears when the file does not exist. 当文件不存在时,将出现错误java.io.FileNotFoundException。 The code below should do this but it comes up with the error "PartB is an incompatible type". 下面的代码应该这样做,但它会出现错误“PartB是一个不兼容的类型”。 I think there is an error in my try and catch code, this the first one I've written and I am at a loss as to why it won't work. 我认为我的尝试和捕获代码有一个错误,这是我写的第一个,我不知道为什么它不起作用。 Any help would be great. 任何帮助都会很棒。 Thankyou. 谢谢。

 ...
  public static void writeHtmlFile()
   {
    try {
             BufferedReader in = new BufferedReader((new FileReader("changedrawer.html")));

     String sLine;
     StringBuilder sb = new StringBuilder();
     while ((sLine = in.readLine()) !=null)
     sb.append(sLine+"\n");
     //Close file 
     in.close();
     //Output on console
     System.out.println(sb.toString());
     }
     catch (PartB FileNotFoundException) //Why is PartB an incompatible type? (PartB is the name
     of the class)

     {  System.out.println ("error");
     }
     ...

您需要将其写为FileNotFoundException PartB ,而不是PartB FileNotFoundException因为FileNotFoundException是类型。

The syntax for a simple "catch" clause is roughly as follows: 简单的“catch”子句的语法大致如下:

} catch (<exception-type> <identifier>) {  
    <optional-statements>
}

The <exception-type> is the name if the exception you are trying to catch, and <identifier> is the name of a local variable that you are declaring to hold the exception instance that you just caught. 如果您尝试捕获异常,则<exception-type>是名称, <identifier>是您声明要保存刚刚捕获的异常实例的本地变量的名称。

In your cause, it should look like this: 在你的事业中,它应该是这样的:

catch (FileNotFoundExceptio ex) {
    System.out.println ("error");
}

... though I'd recommend a more informative error message! ...虽然我建议提供更丰富的错误信息!

(Note that you have to declare a local identifier, even if you are not going to use it. But it is only a couple of characters, especialy if you use the conventional names e or ex .) (请注意,您必须声明一个本地标识符,即使您不打算使用它。但它只有几个字符,特别是如果您使用常规名称eex 。)

您声明一个异常,就像声明任何对象或变量一样:

Exception_Type identifier

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM