Search code examples
javaexceptiontry-catchthrowtry-catch-finally

What is the point of declaring an exception rather than handling it


As far as I understand, if you only declare a checked exception it will propagate through all your methods down to the main method and still interrupt your normal program flow and your program will still stop working. So, why not always handle checked exceptions with try/catch...so that way your program does not stop due to an exception? Why bother declaring an exception in the method's signature? Sorry for my bad English


Solution

  • As far as I understand, if you only declare a checked exception it will propagate through all your methods down to the main method and still interrupt your normal program flow and your program will still stop working.

    Absolutely. And that's a good thing if something's happened that you really can't handle.

    For example, suppose you've got a program which is going to update your database with some data in a file - but you fail to load the file.

    You could just catch the exception, ignore it and still overwrite the data in your database... but that would not be a good thing. As soon as you're in a situation you weren't prepared for, or you fundamentally can't continue sensibly, then stopping is the responsible thing to do.

    Sure, if you can genuinely handle the exception and keep going, that's great - but in my experience, there are relatively few errors where that's the case. If you're writing a server-side application you typically want to abort the request (and give an error to the client). If you're writing a UI then you may want to just abandon the current operation, notify the user and let them keep going... it's a slightly different situation there.

    But unconditionally catching all exceptions and pretending they didn't happen? <shudder>