elchente23 elchente23 - 3 years ago 142
C# Question

Proper way to rethrow an exception

I have the following methods in c#:

void Method1()
{
try
{
Method2();
}
catch(Method2Exception ex)
{
//Log error
}
}

void Method2()
{
if(error)
{
throw(new Method2Exception("error"));
}

//Do something and call method3
try
{
Method3();
}
catch(Method3Exception)
{
//??
}
}

void Method3()
{
//Do something
if(error)
{
throw(new Method3Exception("error"));
}
}


Method3 its gonna be call by different methods and it returns Method3Exception and I need rethrow the exception from Method2 to Method1 but I don't want catch Method3Exception on Method1. what's the best way to do that?

Any suggestions

Answer Source

Alternative way to re-throwing the exception (using throw; as described in other answers) is to wrap the exception in inner exception. As described in MSDN, all custom exceptions should have at least four constructors, and one of them is

public InvalidDepartmentException(string message, System.Exception inner) : base(message, inner) { }

So if all your custom exceptions are like this, you could wrap the exception from Method3 as inner exception:

void Method2()
{
    if(error)
    {
        throw(new Method2Exception("error"));
    }

    //Do something and call method3
    try
    {
        Method3();
    }
    catch(Method3Exception exc)
    {
        throw new Method2Exception("error", exc); // exc is passed as inner exception
    }
}

Then if you want to inspect the inner exception in Method1, you can use property InnerException:

void Method1()
{
    try
    {
        Method2();
    }
    catch(Method2Exception ex)
    {
        if(ex.InnerException != null)
        {
            var message = ex.InnerException.Message;
            // Do what you need with the message
        }
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download