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?
The not-equal-to operator ( != ) returns true if the operands don't have the same value; otherwise, it returns false .
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.
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:
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).
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.
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
}
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