Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C#, how do I know which exceptions to catch?

I've gotten in the habit of using a general catch statement and I handle those exceptions in a general manner. Is this bad practice? If so, how do I know which specific exceptions could be thrown and which ones do I catch?

like image 715
mcass20 Avatar asked Apr 28 '10 13:04

mcass20


People also ask

What does != Mean in C?

The not-equal-to operator ( != ) returns true if the operands don't have the same value; otherwise, it returns false .

What is ?: operator in C?

In other words, we can also say that an operator is a symbol that tells the compiler to perform specific mathematical, conditional, or logical functions. It is a symbol that operates on a value or a variable. For example, + and - are the operators to perform addition and subtraction in any C program.


3 Answers

The methods you run will generally show what exceptions can be thrown. You can then catch accordingly.

If it's your own code, you can generally see what will be thrown, or use the underlying classes exceptions as a guide on what you will need to catch.

I recommend a few links:

  • Exception Handling in C#
  • Try..Catch
  • Exceptions and Exception Handling
like image 107
Kyle Rosendo Avatar answered Oct 24 '22 01:10

Kyle Rosendo


  1. Yes, except in a couple of very specific cases that's bad practice. The one common case I can think of where catching all exceptions isn't a lousy idea is when you're logging a message or a stack trace just before the app is about to tear itself down (or, maybe, you're logging and rethrowing).

  2. Catch only the exceptions you know you can handle. No more, no less. If you don't know an exception can be thrown from a method, you aren't going to handle it properly anyway so don't catch it. Methods and libraries are responsible for documenting exceptions that you should be able to handle. Also, don't catch exceptions that indicate a logic failure, such as NullReferenceException and ArgumentException. These indicate a genuine bug in your software that you should fix, not something that you should handle at runtime.

like image 25
Greg D Avatar answered Oct 24 '22 00:10

Greg D


Yes, that is bad practice. Rule of thumb: "catch the exceptions you are in a position to respond to, let the other ones go."

try {
    File.Open(usersChosenFile, FileMode.Open);
} catch(FileNotFoundException) {
    // tell the user the file is gone, give them a chance to respond
    // this is good
} catch(UnauthorizedAccessException) {
    // this is good too
} catch(Exception) {
    // what did you just catch? Who knows. What if its OutOfMemoryException?
    // Do you really want to deal with that here? Let this one go by
}
like image 24
Matt Greer Avatar answered Oct 24 '22 00:10

Matt Greer