In the following chunk of code the new constructor is documented to throw seven different exception types, including System.IO.PathTooLongException and System.ArgumentException, System.UnauthorizedAccessException and System.SecurityException:
try
{
var fileInfo = new FileInfo(path);
}
catch ???
I'm just trying to ensure that the path is actually an accessible path and nothing bad happens when I try to create a file using this path.
So, the question:
Books and coding guidelines tell me that I shouldn't use catch (Exception) construct, but I face the following situation - I can catch and handle 4 (out of 7) exception types and their handling for every exception types is absolutely the same.
How should this be done?
I can also think of the following solution, but it still looks bad:
catch (Exception exception)
{
Debug.Assert(exception is PathTooLongException || exception is ...);
// (or maybe rethrow it further if there is a type mismatch)
//... Handling code ...
}
You don't have to catch every possible exception around every line of code.
Instead, only catch when you have context and you are prepared to handle and take appropriate action. Otherwise, just let it bubble up.
Catching exceptions (especially deep in the stack in common functions where you don't have enough context to handle) can be problematic. It sometimes leads to swallowing and not appropriately handling. Handle exceptions when you have context.
For that FileInfo exception it depends how deep in that stack it is. If it's in a library where it can be reached via multiple paths and scenarios, you shouldn't handle, what are you going to do at that point? If that's also the case and it bubble all the way out through a deep stack to a GUI performing an operation where you want to handle it, what are you going to catch? Every possible exception of every code path on it's execution path? And, as code changes, you're going to re-evaluate all paths? In a shallow code path (file info dialog that calls that method) it's an easy call but even then you're not going to handle it differently - you're going to display an error dialog or message in panel. Exception types offer the ability to handle differently. In both of those case, you handle exception so I say bah hum bug to that guideline.
What is very clear is you should not throw type Exception. That short circuits the ability to handle differently.
Another related post:
Trying to understand exceptions in C#
Also, you can test the path first with File.Exists(path) or Directory.Exists(path)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With