Search code examples
c#try-catchthrow

To throw or not to throw an exception in C#


Possible Duplicate:
Why catch and rethrow Exception in C#?

I've been scouring the net trying to find the answer to this question - What's the between the two?

try
{
    //Do Something
}
catch
{
    throw;
}

vs

try
{
    //Do Something
}
catch
{
}

or

try
{
    //Do Something
}
catch (Exception Ex)
{
    //Do something with Exception Ex
}

Solution

  • catch --> throw will actually just throw your error, so you will have to catch it somewhere else. This can be useful if you want to catch something first and then throw the error to other methods above.

    Example:

    try
    {
        // do something
    }
    catch
    {
        Console.WriteLine("Something went wrong, and you'll know it");
        throw;
    }
    
    // won't get here anymore, the exception was thrown.
    

    While try --> catch will just let you ignore the error.

    try
    {
        // do something
    }
    catch
    {
        Console.WriteLine("Something went wrong, and you won't know it.");
    }
    
    // continuing happily