12.5. Where to Handle Errors
Part of establishing a consistent error-handling policy is deciding where each error should be handled. One of the (many) beauties of exception handling is that exceptions will continue to bubble up a callstack until they either are handled or reach the top of the callstack and cause the application to fail. That means that each method only has to handle a specific set of exceptions and can leave the rest to be dealt with at a higher level. Each method in the callstack handles errors if it can, and leaves them to the next level up if it cannot. In the event that an exception isn't dealt with, it will cause the application to exit, which is much better for everyone than to have the system continue running in an inconsistent and/or unknown state.
One of the foremost reasons for not catching base-class exceptions is that if you don't know what kind of exception you are handling, you also don't know in what state you are leaving the application to continue. Far better to exit gracefully (or even catastrophically) than to continue in a state that might lead to incorrect results or data loss.
For example, take another look at the following file-reading code. The method that actually reads from the network source can't do very much to recover if the network source cannot be read.
public Stream ReadFileFromNetwork(string fileName) { if (!Uri.IsWellFormedUriString(fileName, UriKind.Absolute)) throw new ArgumentException( "The file name must be in the form of ...
Get Code Leader: Using People, Tools, and Processes to Build Successful Software now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.