Search code examples
javaexceptiontry-catchthrow

A basic question about throwing Exceptions


In Java I have a method 'exampleMethod' that calls 'foo' foo throws an Exception under certain circumstances. Am I right in believing that exampleMethod doesn't need a try, catch block for this call to foo and that the exception would be immediately thrown to whatever calls 'exampleMethod', and that in the case of a sequence of methods that throw the exception it would go all the way back until a try,catch block is found to handle it or it finds a method that doesn't throw it and crash the program?

    exampleMethod(String message) throws ExampleException {
        foo(message);
    }

    public foo(String message) throws ExampleException{
        if(message == null){
           throw new ExampleException();}
    }

Solution

  • Yes, you are correct. exampleMethod does not need a try-catch block when calling foo and will instead throw the exception to whatever called it. You are also correct that an exception can continue to be thrown until it reaches a try-catch or crashes the program.