[WF4]Try Catch activity in code

Use Try Catch activity in the pure C# way. First, Create a workflow with Try-Catch in pure C# code:

using System;
using System.Activities;
using System.Activities.Statements;
namespace ErrorHandling {
    public class ErrorHandlingWorkflow{
        public Activity GetInstance() {
            Variable<int> divisor = new Variable<int>("divisor", 10);
            Variable<int> dividend = new Variable<int>("dividend", 0);            
            Variable<int> result = new Variable<int>("result");
            DelegateInArgument<DivideByZeroException> eia = 
new DelegateInArgument<DivideByZeroException>();             Activity workflow = new Sequence() {                 Variables = { divisor, dividend, result },                 Activities ={                     new TryCatch{                         Try=new Assign{                             To=new OutArgument<int>(result),                             Value=new InArgument<int>(                                 aec=>divisor.Get(aec)/dividend.Get(aec)                             )                         },                         Catches={                             new Catch<DivideByZeroException>{                                 Action=
new ActivityAction<DivideByZeroException>{                                     Argument=eia,                                     Handler=new Sequence{                                         Activities={                                             new WriteLine{
Text="Divide By Zero Exception"
},                                         }                                     }                                 },                             }                         },                         Finally=new WriteLine{Text="finally,calculation done"}                     }                 }             };             return workflow;         }     } }

Then, Call it in Main method:

using System.Activities;
namespace ErrorHandling {
    class Program {
        static void Main(string[] args) {
            ErrorHandlingWorkflow errorHandlingWorkflow=
                new ErrorHandlingWorkflow();
            WorkflowInvoker.Invoke(errorHandlingWorkflow.GetInstance());
        }
    }
}

Result:

blog comments powered by Disqus