Search code examples
javaexceptiontry-catchthrowthrows

Throwing Java Exceptions


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.


Solution

  • If SomeException is a checked exception you have to either

    • Use a try{}catch block or
    • Declare that your method throws it.

    You 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.