You have to catch the exception at the point in the code where you can do something. Often the code that throws the exception is unable to handle the problem, but the method that called this code, or the method called the method that called this code, can gracefully handle the problem.
Let's say you have code that tries to open a file and read some data, and it throws an exception if the file does not exist. The code in this area cannot do much, but a guarantee, but a few frames in the call stack, the calling method may say: โOh, well, an exception has been thrown. Instead, I will try this alternative fileโ or โI assume that this file was notโ , t exists, so I will continue and create a new one. "
This is really one of the big advantages of exceptions: they free the developer from having to handle all possible errors. You can write code with the expectation that it will work most of the time, and your code should not be cluttered with a lot of error handling. While you are advertising the exceptions that you can throw, you can make the code higher in the call stack by encountering problems in a way that goes well with everything that this code is trying to do.
Caleb
source share