When a method throws and exception, do we need to have a try block inside the method?
For example,
public void foo() throws SomeException{
try{
// content of method
}
}
Is the try block required? Or, is the method able to throw a SomeException without it :
public void foo() throws SomeException{
// content of method
}
This is the case when we are not explicitly throwing a SomeException with throw.
If SomeException
is a checked exception you have to either
try{}catch
block orYou do not have to do both, either example you show in your question works just fine.
The difference is that with the try
clause you handle the SomeException
yourself, whereas by declaring that your own method throws
it you delegate the responsability of handling the SomeException
to the calling method.