Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# exception handling, which catch clause to use? [duplicate]

Possible Duplicate:
Catching specific vs. generic exceptions in c#

Here's an example method

private static void outputDictionaryContentsByDescending(Dictionary<string, int> list)
{
    try
    {
        //Outputs entire list in descending order
        foreach (KeyValuePair<string, int> pair in list.OrderByDescending(key => key.Value))
        {
            Console.WriteLine("{0}, {1}", pair.Key, pair.Value);
        }
    }
    catch (Exception e)
    {
        MessageBox.Show(e.Message, "Error detected", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

I would like to know what exception clause to use apart from just Exception and if there is an advantage in using more specific catch clauses.

Edit: O.k thanks everyone

like image 918
Elliot678 Avatar asked Jan 17 '12 16:01

Elliot678


People also ask

What is C in simple words?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

Is C language easy?

Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

What is %d in C programming?

In C programming language, %d and %i are format specifiers as where %d specifies the type of variable as decimal and %i specifies the type as integer. In usage terms, there is no difference in printf() function output while printing a number using %d or %i but using scanf the difference occurs.


3 Answers

Catching individual types of Exceptions in your statement will allow you to handle each in a different way.

A blanket rule for Exception may be useful for logging and rethrowing Exceptions, but isn't the best for actually handling Exceptions that you may be able to recover from.

try
{
    // open a file specified by the user
}
catch(FileNotFoundException ex)
{
    // notify user and re-prompt for file
}
catch(UnauthorizedAccessException ex)
{
    // inform user they don't have access, either re-prompt or close dialog
}
catch(Exception ex)
{
    Logger.LogException(ex);
    throw;
}
like image 167
Justin Niessner Avatar answered Sep 19 '22 07:09

Justin Niessner


You should only really catch exceptions that you are expecting that code may throw. That way, if it throws something you didn't expect, it may either be something critical; something that should bubble up the call stack and possibly crash the application; or something you have not thought of.

For example, you may wish to handle IOExceptions thrown by I/O code so that you can relay the problem back to the user. However, the same operations may throw something more critical such as an AccessViolationException. In this case, you might want the program to terminate, or handle the problem in a different way.

Generic exception handling should only really be used in cases where you do not care what error occurred, and subsequently don't want it affecting the rest of your process.

like image 34
Samuel Slade Avatar answered Sep 19 '22 07:09

Samuel Slade


The only potential cause for an exception that I see in your example is if list is null. OrderByDescending() should return an empty IEnumerable<> rather than a null reference.

If I read that correctly, it might make more sense to catch NullReferenceException:

try
{
...
} catch (NullReferenceException exception)
{
  MessageBox.Show(...);
}

However, this really depends on the needs of your application. If your intention is just to alert the user or to log all exceptions, catching the Exception class is fine. If you need special handling for different types of exceptions - such as sending an email alert instead of just logging the message - then it makes sense to use specific exception types:

try
{
} 
catch(NullReferenceException e)
{
//...
} 
catch(StackOverflowException e)
{
//...
}
catch(Exception e)
{
/// generic exception handler
}
like image 27
3Dave Avatar answered Sep 21 '22 07:09

3Dave