0

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
}

2 Answers 2

3

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!");
}
Sign up to request clarification or add additional context in comments.

2 Comments

And If the exception is an unchecked exception, you don't need the throws.
Also, add the constructor with parameter to MyException.
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
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.