Question

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.

Was it helpful?

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

OTHER TIPS

A try { ... } catch (Exception) { ... } block will catch all exceptions of any type as it is the base/root exception type in .NET.

It is, however, considered bad practice to do so:

http://msdn.microsoft.com/en-us/library/ms182137.aspx

Exception is the base implementation of all exceptions, any .NET exception type must inherit from the Exception class. As per the MSDN:

This class is the base class for all exceptions. When an error occurs, either the system or the currently executing application reports it by throwing an exception that contains information about the error. After an exception is thrown, it is handled by the application or by the default exception handler.

However, you usually want to follow best practice of not catching such a broad category as Exception. check here for some good guidelines:

In reality though, there are times where you really don't care if it fails as far as the code execution goes, you just want to know if it failed or not. However, you would want to examine your code to see if what you are calling is even needed if you don't care about how or why it failed.

Simply put though, exception will catch all objects that derive from Exception.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top