jsh6303
jsh6303

Reputation: 2040

Priority of throws and throw for same exception

I was curious which one of throws and throw has higher priority, when it comes to the same type of exception (although this does not seem likely to occur in real-life examples). Below is the example I came across:

public void sample() throws ArithmeticException{
    //Statements

    .....

    //if (Condition : There is an error)
    ArithmeticException exp = new ArithmeticException();
    throw exp;
    ...
}

Upvotes: 1

Views: 508

Answers (1)

lschuetze
lschuetze

Reputation: 1218

The keyword throws means that a method can throw an exception. A method that declares an exception does not have to throw them. It is just that they can be thrown. Thus, the compiler enforces the caller to catch those exceptions.

So throw is actually really throwing an exception. It can be used when there is no throws declaration, too.

Upvotes: 2

Related Questions