What's the best practice for handling exceptions?

if I have a specific exception that I expect when it happens; and to handle it, for example, I decided to display an error message when it occurs, what would be better to do and why?

Explanatory code:

try
{
    string result = dictionary[key];
}
catch (KeyNotFoundException e) 
{ 
    //display error
}

      

or

if(!dictionary.ContainsKey(key))
{
    //display error
}

      

+2


source to share


10 replies


Typically, exceptions are used to indicate exceptional conditions - which usually does not happen, but your program should still handle gracefully (for example, the file is not available or read-only, the network connection fails). Normal control flow, such as checking a value in a dictionary, should not use exceptions if an equivalent function exists that has the same effect without using exceptions.

Having extra try / catch statements in your code also makes it less readable, and having exception handlers around a block of code imposes certain restrictions on the CLR, which can lead to performance degradation.

In your example, if the dictionary is expected to have a specific key value, I would do something like



string result;
if (!dictionary.TryGetValue(key, out result)
{
    // display error
    return;   // or throw a specific exception if it really is a fatal error
}

// continue normal processing

      

This is much clearer than just an exception handler around element access

+12


source


Neither.

The second option is better than the first. Since you expect this to happen normally, it is best to avoid an exception. Exceptions should be preferably used only in exceptional situations, that is, something that you cannot easily predict and test.



The TryGetValue method is the best option, as it does validation and fetch:

if (dictionary.TryGetValue(key, out result)) {
   // use the result
} else {
   // display error
}

      

+7


source


The second approach is better. Throwing exceptions can be very costly.

+3


source


The second approach is better for at least three reasons:

1) It's clearer. As a reader of your code, I expect the exception to indicate that something went wrong, even if it is being handled.

2) When debugging with Visual Studio, this is the usual throwing of all exceptions, which makes it rather annoying to handle code that always throws an exception.

3) The second version is faster, but the effect is very small if you don't throw many exceptions per second in a time-critical piece of code.

+2


source


The second approach is probably better. Remember that exceptions are used for exceptional circumstances. Use this principle for your solution:

  • If you require a key to exist in the dictionary as an application invariant, then assume it exists and deals with an exception if it doesn't exist.
  • If your application code does not require this entry in the dictionary, call first ContainsKey()

    .

I guess the latter is probably the right course of action.

Disclaimer: I generally avoid recommending that performance should be the primary consideration here. Just let performance influence your decision once you've proven you have a bottleneck! Anything prior to this premature optimization will lead to unnecessary application code.

+2


source


The second approach is better because throwing exception and hanlding succeeds. Emissions above 100 per second are likely to have a noticeable impact on most applications. Consider Exceptions and Performance .

+1


source


Exception handling is most useful when you need to provide an easy way out of a complex situation - it can greatly simplify your code and reduce the chance of errors in the root directory.

It offers little benefit in very simple situations like this, and because of its performance penalty should not be used in such cases.

+1


source


It all depends on what you are doing and what the particular code is doing.

As the comment says, exceptions should be used for exceptional conditions. Let's take a file recording as an illustration. If checking for the existence of a file slows down your application and / or the absence of a file is a serious problem, then resolve the exception and catch it. If it is not that important or if it is not a problem to recreate the file, then check the file existence first.

I saw that he argued that all error handling should be done with exceptions (most recently in Clean Code by Robert Martin ), but I disagree.

0


source


It depends a lot on what the dictionary is supposed to do. If there is a high probability that the key will not be found due to program design, then you should make a trygetvalue. However, if the design of your program is such that not finding a key is an exceptional event, then you should use an exception handler method.

0


source


Just a reminder. This is no exception. An exception is something like "no / etc on my UNIX machine". If you go wrong, you will write the wrong code shown above.

-2


source







All Articles