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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With