2012-06-18 127 views
0

我在写一个可以打开和编辑文件的java应用程序。但是,如果文件的布局不正确,我希望它给我一个错误。 我的文件看起来像这样:文件布局异常

Title 
X Y 
Name 
X times line 

如果看着try和catch但那不给我正确的解决方案给予如下错误:

"There is no X or Y specified" 

"There is nog Title in this file" 

请告诉我选择做这个?

+0

使用,如果和其他 – Azulflame

+1

,有工作代码。 else循环将包含您的错误,并使用嵌套的if循环来捕获错误的类型,因为我们将作为嵌套的else循环包含一般错误消息 – Azulflame

回答

1

创建属于自己的Exceptionextends Exception。有时这被称为域例外,因为它只适用于您的问题域。

这里是你如何编写它的一个例子:

public class FileLayoutException extends Exception { 
    // extending Exception means you can throw it and declare it to be thrown 
} 

声明你的方法把它扔到:

public void readFile() throws FileLayoutException { 
    // some impl 
} 

然后,当你发现一个问题,像这样使用:

throw new FileLayoutException("There is no X or Y specified"); 

throw new FileLayoutException("There is no Title in this file"); 


因为你的错误条件“​​文件相关的”,你可以考虑,如果环路内侧延伸的IOException代替Exception