myacobucci
myacobucci

Reputation: 185

Java, parent class, method with an exception throw

I have a method, how do I throw an exception. As opposed to try and catch.

Its a basic void method which reads in a file,

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

Upvotes: 0

Views: 4697

Answers (2)

Supericy
Supericy

Reputation: 5896

Easy as:

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

or if you want a custom exception:

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

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

Upvotes: 3

Arun P Johny
Arun P Johny

Reputation: 388406

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

Upvotes: 2

Related Questions