0

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

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

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

2 回答 2

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!");
}
于 2013-04-26T03:02:23.743 回答
2

As a first step, I think you need to go through java Exceptions

It depends on what kind of exception you want to throw

If you want to throw an unchecked exception

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

If you want to throw an checked exception

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
    }
}
于 2013-04-26T03:06:59.937 回答