How to get Type of Exception in C#

I know this is an older post, but if you are going to handle all exceptions the same way and/or are using the information for error reports or something similar (instead of notifying the user of the specifics) you can use the following.

try
{
    //do something here
}
catch(Exception ex)
{
    MessageBox.Show(ex.GetType().ToString()); //will print System.NullReferenceException for example
}

You need to know at code-time what exceptions to expect, in order to catch them accordingly. As Dimitrov stated, a SQLException is thrown when the connection to an SQL server fails, so catching that specifically is a good tactic.

You want to catch the various exceptions in order, like so:

try 
{
    //some code
}
catch(TypeOfException exOne) 
{
    //handle TypeOfException someway
}
catch (OtherTypeOfException exTwo) 
{
    //handle OtherTypeOfException some other way
}
catch (Exception ex) 
{
    //handle unknown exceptions in a general way
}
finally 
{
    //any required cleanup code goes here
}

Try to put the most unusual exceptions at the top, working your way down the list towards more common ones. The catch sequence is sequential - if you put catch(Exception) at the top, it will always catch on that line no matter what exceptions you code for beneath it.


You could try catching a SQLException:

try 
{
    // Try sending a sample SQL query
} 
catch (SQLException ex) 
{
    // Print error message
}