Pawel K
Pawel K

Reputation: 43

Throwing general exception in Java

This is for an online tutorial in throwing exceptions

I am trying to do something like this:

int power(int n, int p){
        try
        {
            return (int)Math.pow(n,p);
        }
        catch(Exception e)
        {
            throw new Exception("n and p should be non-negative");
        }
    }

But I get the error

error: unreported exception Exception; must be caught or declared to be thrown

Upvotes: 4

Views: 3409

Answers (1)

Eran
Eran

Reputation: 393771

Exception is a checked exception, which means that if a method wants to throw it, it must declare it in a throws clause.

int power(int n, int p) throws Exception {
    try
    {
        return (int)Math.pow(n,p);
    }
    catch(Exception e)
    {
        throw new Exception("n and p should be non-negative");
    }
}

Upvotes: 5

Related Questions