Showing posts with label exception handling. Show all posts
Showing posts with label exception handling. Show all posts

Fault Exceptions in WCF


Exceptions thrown by WCF service are treated as Fault exceptions. As a developer we should gracefully handle these kind of exceptions. Let's take a look at this by an example/

Service Contract -
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
[ServiceContract]
    public interface IService2
    {
        [OperationContract]
        [FaultContract(typeof(MyException))]
        [DebuggerStepThrough]
        MyException GetData(int value);
    }

    [DataContract]
    public class MyException 
    {
        [DataMember]
        public bool Result { get; set; }

        [DataMember]
        public string ErrorMessage { get; set; }

        [DataMember]
        public Exception MyInnerException { get; set; }

        [DataMember]
        public string ClientMessage { get; set; }
    }


Service Implementation -
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class Service1 : IService2
    {
       
        public MyException GetData(int value)
        {
            MyException mx = new MyException();
            try
            {
                double a = 44;
                if (value == 0)
                {
                    throw new DivideByZeroException();
                }
                double res = a / value;
                mx.ClientMessage = "Everything is well";
                mx.Result = true;
                return mx;
            }
            catch (DivideByZeroException dvex)
            {
                mx.Result = true;
                mx.ClientMessage = "Divide by zero";
                mx.MyInnerException = dvex;
                mx.ErrorMessage = dvex.StackTrace;
                throw new FaultException<MyException>(mx, dvex.ToString());
            }                    

        }
    }


Client (aspx.cs page) -

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
try
            {
                FaultContractsDemo.ServiceReference1.Service2Client o = new ServiceReference1.Service2Client();
                MyException data = o.GetData(0);
                if (data.Result)
                    lblMessage.Text = "All is well";
            }
            catch (FaultException<MyException> ex)
            {
                lblMessage.Text = ex.Detail.ClientMessage;
            }


The service layer throws an exception, but client never recieves any. I am getting unhandled exception like,
The underlying connection was closed: The connection was closed unexpectedly.
 WCF does not like serializing the DivideByZeroException or any root exception caused at service layer, which is necessary to get it across the wire. Commenting out this would work as expected.

Can multiple catch blocks be executed ?

One of my acquaintance asked this question. Initially I got confused that is it really possible.
The answer to this question is "NO". Here is a program in support with this answer.

    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                int numerator = 20;
                int denominator = 0;
                int result = numerator / denominator;
            }
            catch (DivideByZeroException de)
            {
                Console.WriteLine("You are trying to divide by number 0");
            }
            catch (Exception ex)
            {
                Console.WriteLine("This is a general exception.");
            }
            finally
            {
                Console.WriteLine("You are in finally block.");
            }
        }
    }

The output of this program is;
You are trying to divide by number 0
You are in finally block.

This means that when an exception occurs, and is handled with the specific type it executes the statements in the catch block and leaves the control to finally block, if exists.

It is not possible to execute multiple catch blocks.

Returning from finally



Can we return from finally block? If your answer is yes, take a look at this code.
We have a function body as ;

try
{  
   return "From try"; 
}
catch (Exception ex)
{ 
   return "From Catch"; 
}
finally
{
   return "From Finally"; 
}

If this is enclosed in a function and we are giving call to the function,
what will be the return value of this statement?
And the answer is, it will give a compilation error, as we cannot return from finally block.

Labels

.net .Net Instrumentation logging .net localization Agile amazon amazon elasticache amazon services AppDomain Application Domain architecture asp ASP.Net authentication authentication mechanisms Byte order mark c# cache canvas app cdata certifications class classic mode cloud cloud computing cluster code-behind Combobox compilation Configuration providers configurations connection connectionString constructors control controls contructor CSV CTS .net types conversion database DataGridView DataSource DataTable DataType DBML delegates design pattern dispose double encoding Entity framework Events exception handling expiry fault contracts fault exceptions function pointers functions generics help HostingEnvironmentException IIS inner join instance management integrated mode javascript join left outer join LINQ LINQ join LINQ to SQL memory leak methods microsoft model driven app modes in IIS MSIL multiple catch blocks no primary key Nullable Osmos Osmotic Osmotic communication Osmotic communications page events page life cycle partial class PMI powerapps preserve precision points private contructor ProcessExit Project management properties property protect connectionString providerName providers query regular expression repository Responsive Web Design return type run-time RWD Saas self join session session expiry sessions singelton singleton pattern software as a service source control system SQLMetal string time management time-boxing toolstrip ToolStrip controls ToolStripControlHost tortoise SVN ToString() try catch finally update wcf web application web design web site web.config where-clause xml

Pages