exception errors c# code example

Example 1: exception in asp.net c#

try
{
    //code that may raise an exception
}
catch //cannot have both catch and catch(Exception ex)
{ 
    Console.WriteLine("Exception occurred");
}
catch(Exception ex) //cannot have both catch and catch(Exception ex)
{
    Console.WriteLine("Exception occurred");
}

Example 2: how to get error code from exception in c#

try {
	// some operation causing an exception
}
catch (SqlException e) {
	if (e.ErrorCode == 0x80131904)
      	// ...
		return null;
	throw;
}

Example 3: exception in asp.net c#

try
{
    // put the code here that may raise exceptions
}
catch
{
    // handle exception here
}
finally
{
    // final cleanup code
}