Reputation: 1243
I have question on Java throw exception at class method definition:
public void someMethod () throws SomeException {
try{
...
}catch (SomeException e ){
....
}
}
When we declare throw SomeException
at the method declaration, do we still have to try/catch
in the body or, can we just use throw new SomeException
like this:
public void someMethod () throws SomeException {
// do something
throw new SomeException() ;
}
what is the correct way to throw exception when we have throw Exception
at the method declaration.
Upvotes: 2
Views: 393
Reputation: 234665
Your prototype public void someMethod () throws SomeException
is mandating that someMethod
will only throw exceptions of type SomeException
. (Or any exception classes derived from SomeException
).
Therefore you do not need to catch that particular exception in your function, but you will need to catch all others.
Upvotes: 1
Reputation: 285403
No, you do not need to catch the exception that you throw as long as you're not changing it or selectively throwing it only in some situations when the exception occurs. So this is often perfectly fine:
public void someMethod () throws SomeException {
// do something
throw new SomeException() ;
}
Although it's often good to give your SomeException class a constructor that takes a String parameter, and then pass that String to the super constructor to allow your exception to be able to pass more information through.
Upvotes: 5