Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it bad programming style to have a single, maybe common, generic exception?

so in my program I have parts where I use try catch blocks like this

try
{
  DirectoryInfo dirInfo = new DirectoryInfo(someString); 
 //I don't know if that directory exists
 //I don't know if that string is valid path string... it could be anything

 //Some operations here
}
catch(Exception iDontCareWhyItFailed)
{
  //Didn't work? great... we will say: somethings wrong, try again/next one
}

Of course I probably could do checks to see if the string is valid path (regex), then I would check if directory exists, then I could catch various exceptions to see why my routine failed and give more info... But in my program it's not really necessary. Now I just really need to know if this is acceptable, and what would a pro say/think about that. Thanks a lot for attention.

like image 243
m0s Avatar asked Apr 05 '10 00:04

m0s


Video Answer


2 Answers

  • write "mainline" code to handle expected cases.
  • write exception handling code to... wait for it... handle exceptional cases. That's why it's called "exception handling code". :-)

If a mainline, expected, everyday case is that the path doesn't exist, then write mainline code that checks whether the path exists. If an unexpected, bizarre, exceptional circumstance is that the file exists but has been locked by another user, write an exception handler that handles that exception.

like image 139
Eric Lippert Avatar answered Nov 08 '22 15:11

Eric Lippert


You shouldn't use exceptions for flow control, because it hurts performance and exceptions are not designed for that purpose. Instead, you should test the Exists property to check that the directory exists

like image 21
Thomas Levesque Avatar answered Nov 08 '22 14:11

Thomas Levesque