2013-04-26 139 views
0

我有一个方法,我该如何抛出异常。而不是尝试和捕捉。Java,父类,抛出异常的方法

它的一个基本无效方法,它读取一个文件,

public void method(String filename){ 
//does some stuff to the file here 
} 

回答

3

容易为:

public void method(String filename) throws Exception 
{ 
    if (error) 
     throw new Exception("uh oh!"); 
} 

,或者如果你想有一个自定义异常:

class MyException extends Exception 
{ 
    public MyException(String reason) 
    { 
     super(reason); 
    } 
} 

public void method(String filename) throws MyException 
{ 
    if (error) 
     throw new MyException("uh oh!"); 
} 
+0

取决于你想扔

什么样的异常。如果该异常是一个未经检查的例外,你不需要'抛出'。 – NilsH 2013-04-26 03:06:09

+0

另外,将带有参数的构造函数添加到MyException中。 – acdcjunior 2013-04-26 03:08:40

1

作为第一一步,我认为你需要经过java Exceptions

,如果你想抛出一个未经检查的异常

public void method(String filename){ 
    if(error condition){ 
     throw new RuntimeException(""); //Or any subclass of RuntimeException 
    } 
} 

如果你想抛出一个checked异常

public void method(String filename) throws Exception{ //Here you can mention the exact type of Exception thrown like IOExcption, FileNotFoundException or a CustomException 
    if(error condition){ 
     throw new Exception(""); //Or any subclass of Exception - Subclasses of RuntimeException 
    } 
}