Click here to Skip to main content
15,905,504 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
I know, we can use try-catch block to handle exceptions. But I have some doubts in the usage of Try-Catch.
What is the difference between

C#
try
{
   //Some code
}
catch
{

}


and

C#
try
{
 //Some code
}
catch(Exception)
{

}


and

C#
try
{
 //Some code
}
catch(Exception oops)
{

}


In my program, I need to catch all exceptions and I don't want to log them. From the above mentioned Try-Catch blocks, which should be used?
Posted

There's no difference between the first and the second block, because all exceptions inherit from Exception. If you change Exception into another exception, OutOfMemoryException for example, then the code in the catch block will only be executed if the exception which is thrown a OutOfMemoryException is.

In the third block, the exception which is thrown is also stored in a variable, so you can get the error message for example:
C#
try
{
    // some code
}
catch (Exception ex)
{
    Console.WriteLine(ex.Message); // writes the error message to the console
}


[EDIT]

Kaizen202 wrote:
In my program, I need to catch all exceptions and I don't want to log them. From the above mentioned Try-Catch blocks, which should be used?

If you don't need to specify a exception type, and if you don't want to log them, then use
C#
try
{
    // some code
}
catch
{

}

And if you need to specify an exception type, but if you don't want to log them, then use
C#
try
{
     // some code
}
catch (OutOfMemoryException) // change OutOfMemoryException into the type of the exception which you need to specify
{

}

But if you need to log them, then use
C#
catch (Exception ex) // change Exception into the type of the exception which you want to log

Hope this helps.
 
Share this answer
 
v2
All three ways will work the same. Generally speaking, unless you want to do something with the exception, such as log it, the first block will work just fine. You can use the catch(Exception) syntax when you want to deal with different types of error in different ways. For example:

C#
try
{

}
catch (AccessViolationException oops)
{

}
catch
{

}


which means that you will deal in a specific way for errors of type AccessViolationException while you will deal in the same way with all other types of errors.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900