try/catch versus throws Exception

Viewed 100590

Are these code statements equivalent? Is there any difference between them?

private void calculateArea() throws Exception {
    ....do something
}

private void calculateArea() {
    try {
        ....do something
    } catch (Exception e) {
        showException(e);
    }
}
10 Answers
private void calculateArea() throws Exception {
    ....do something
}

This throws the exception,so the caller is responsible for handling that exception but if caller does not handle the exception then may be it will given to jvm which may result in abnormal termination of programe.

Whereas in second case:

private void calculateArea() {
    try {
        ....do something
    } catch (Exception e) {
        showException(e);
    }
}

Here the exception is handled by the callee,so there is no chance of abnormal termination of the program.

Try-catch is the recommended approach.

IMO,

  • Throws keyword mostly used with Checked exceptions to convince compiler but it does not guarantees normal termination of program.

  • Throws keyword delegate the responsibility of exception handling to
    the caller(JVM or another method).

  • Throws keyword is required for checked exceptions only ,for unchecked exceptions there is no use of throws keyword.

Related