Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Class Library Exception Handling

Can I do this in a c# class library to handle exceptions that may occur during the execution of a class library code itself? I'm new in writing class libraries and exception handling within it. Please advice.

private void MethodName(String text)
    {
        try
        {
            ..............
            ..............
            ..............
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message.ToString());
        }
    }

I've searched in google and stackoverflow, but did not find any article whether I'm allowed to handle exceptions in class libraries this way or if it is not a recommended way to do it. But it works. May be a dumb question, but I have this doubt.

Thanks.

like image 834
Vinay Sathyanarayana Avatar asked Feb 16 '23 18:02

Vinay Sathyanarayana


1 Answers

Yes you can do that, but in general you should only catch exceptions if you are going to do something with it - i.e. swallow it or add value to it (by transforming, wrapping or logging it).

Using your example method, you should throw an exception if text is null and your method expects a value. Other than that you should let exceptions bubble out for the caller to handle unless you are going to do something with it, or it is an expected exception that you intend to suppress.

You also shouldn't throw a new exception, instead just use the throw keyword to rethrow the current exception:

catch (Exception ex)
{
    //do something

    throw;
}
like image 124
slugster Avatar answered Feb 20 '23 11:02

slugster