Search code examples
c#.netweb-servicestry-catchsystem.net.webexception

System.Net.WebException vs. System.Exception


I am calling a SOAP web service in C#

I am using try-catch to catch all exceptions thrown by the web service call. Will the following code:

try
{
    Webservice.Method();
}
catch (Exception)
{
    //Code
}

be able catch all exceptions including web based exceptions like web service not available, internet not connected, wrong response code etc. or should I also use Catch(WebException) if System.Exception does not catch exceptions of type System.Net.WebException. Like:

try
{
    Webservice.Method();
}
catch (WebException)
{
    //Code for web based exceptions
}
catch (Exception)
{
    //Code
}

I do not want separate code for different exceptions. Just one message box stating "error occurred" is good enough for me for all types of exceptions.


Solution

  • if System.Exception does not catch exceptions of type System.Net.WebException.

    System.Exception will catch the WebException since System.Exception is a base class.

    I do not want separate code for different exceptions. Just one message box stating "error occurred" is good enough for me for all types of exceptions.

    In that particular case even an empty catch block would be enough (apart from catching in System.Exception). But generally it is not considered a good practice.

    try
    {
        Webservice.Method();
    }
    catch 
    {
        // Show error
    }
    

    You may see: Best Practices for Exceptions