简体   繁体   中英

System.ServiceModel.FaultException<DefaultFaultContract not catching some exceptions

I am having a code function that has two catch blocks. Am posting the code below:

public void UpdateGroup(String strSiteID, String strGroup,  int row)
        {
            try
            {
                Console.WriteLine("UpdateGroup");
                Excel1.MWMClient.MWMServiceProxy.Group group = new Excel1.MWMClient.MWMServiceProxy.Group();
                group.name = "plumber";
                group.description = "he is a plumber";              
                Console.WriteLine(groupClient.UpdateGroup(strSiteID, group));
                ExcelRecorder(0, null, null, row);
            }
            catch (System.ServiceModel.FaultException<DefaultFaultContract> ex)
            {
                ExcelRecorder(ex.Detail.ErrorCode, ex.Detail.Message, ex.Message, row);
            }
            catch (Exception ex)
            {
                ExcelRecorder(0, "", ex.Message, row);
            }
            finally
            {
                System.GC.Collect();
            }
        }

I thought that the first catch block was enough to catch all the possible exceptions that can occur in my code. But I notice that, at times, the first catch block is not catching some general exceptions. That is why I added second catch block. Why is it happening? Why can't my first catch block cover all exceptions?

Why is it happening? Why can't my first catch block cover all exceptions?

Because by default, when there's no any fault contracts, defined for particular service operation, non-generic FaultException will be thrown at service side (and it will be caught at client side).

The Exception class System.ServiceModel.FaultException can only handle contractually specified Faults

You should be having a statement similar to the one below in your code

throw new FaultException<DefaultFaultContract>(<parmaters>);

which is causing the exception to be handled by the first catch block. When you don't have a operation fault contractually specified,it will be handled by the generic Exception class(second catch block),from which all exception types derive.

Please do check for the code samples given on this page. http://msdn.microsoft.com/en-us/library/ms576199.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM