hi and thanks for reading. im a newbie in programming and C# and sockets programming. in my code i try and catch problems to provide fault tolarence in my app. the following:
catch (ArgumentNullException e)
{
OnNetworkEvents eventArgs = new OnNetworkEvents("Network Unavailable", e.Message);
OnUpdateNetworkStatusMessage(this, eventArgs);
}
catch (EncoderFallbackException e)
{
OnNetworkEvents eventArgs = new OnNetworkEvents("Network Unavailable", e.Message);
OnUpdateNetworkStatusMessage(this, eventArgs);
}
catch (SocketException e)
{
OnNetworkEvents eventArgs = new OnNetworkEvents("Network Unavailable", e.Message);
OnUpdateNetworkStatusMessage(this, eventArgs);
}
catch (ArgumentOutOfRangeException e)
{
OnNetworkEvents eventArgs = new OnNetworkEvents("Network Unavailable", e.Message);
OnUpdateNetworkStatusMessage(this, eventArgs);
}
catch (ObjectDisposedException e)
{
OnNetworkEvents eventArgs = new OnNetworkEvents("Network Unavailable", e.Message);
OnUpdateNetworkStatusMessage(this, eventArgs);
}
i was just wondering if i can replace this repetitive code with one single:
catch (Exception e) { handle here}
would this work?
thanks again.
No, never catch System.Exception. I feel like a broken record today, but I really can’t stress this enough. You cannot handle an
OutOfMemoryExceptionorAccessViolationException, so don’t catch it!As for the example code, I have strong doubts that an
ArgumentNullExceptionorArgumentOutOfRangeexception would correspond to a network error. If it does, it likely means that the component that really should be catching this exception, isn’t.“Fault tolerance” does not mean “eat every exception so the app doesn’t crash” – it means actually knowing the things that can go wrong and handling them correctly.