which is a better practice at exception handling?

c#, exception

Solution

Generally, exceptions are used to indicate exceptional conditions - something that would not normally occur, but your program still needs to handle gracefully (eg a file being inaccessible or readonly, a network connection going down). Normal control flow, like checking for a value in a dictionary, should not use exceptions if there is an equivalent function that has the same effect without using exceptions.

Having extra try/catch statements in the code also makes it less readable, and having exception handlers around a block of code puts certain limitations on the CLR that can cause worse performance.

In your example, if it is expected that the dictionary will have a certain 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 a lot clearer than just having an exception handler round an element access

Problem

if I have a specific exception that I expect when it is going to occur; and to handle it for example I chose to display an error message upon its occurance, which 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 } ```

Original source