Declaring or surrounding the exception with try/catch block in java

Java says that if we throw a checked exception from a method, then either we must declare it or surround it with try/catch block.
I don’t understand why is it declare or surround it with try/catch block, because just by declaring the exception we can’t handle the exception but when we surround it with try/catch block we can handle it.
If above is the case then how one is considered as an alternative to another?

Answer

Two options are available
1. Throw the exception -> This means that if the exception condition occurs, the program expects the caller to handle it.
2. Try/catch -> this means that the method itself will handle it.

Difference is subtle and yes, at times we catch the exception thrown by us in the next layer. But if you consider these statements carefully, that is the core difference between the two approaches.

In large teams, we often have sub teams working on layers. The inner layers may just choose to throw the exception and stop further execution of flow. Outer layers are supposed to catch it and show a graceful error message or graceful way to handle those exceptions so that user does not get to see Java stack trace.

Hope this helps.

Leave a Reply

Your email address will not be published. Required fields are marked *