Java,父类,抛出异常的方法

时间:2013-04-26 03:01:32

标签: java exception

我有一个方法,如何抛出异常。与尝试和捕获相反。

它是一个读取文件的基本void方法,

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

2 个答案:

答案 0 :(得分: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!");
}

答案 1 :(得分:2)

作为第一步,我认为您需要通过java Exceptions

这取决于你想抛出什么样的异常

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

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

如果要抛出已检查的异常

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
    }
}