Saturday, February 28, 2015

Task Exceptions


using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TaskExceptions
{

    public partial class Form1 : Form
    {
        //How do we handle an exception that is thrown in a method
        //If an exception is thrown in a method, the method itself could 
        //catch the exception. If not the caller of this method will 
        //need to either catch it or let it bubble up to previous caller
        //If none of the method in the chain of calls catches the 
        //exception, it bubbles up to the system. 
        //The operating system pops a message alerting you to either continue or cancel
        //the application. 
        public Form1()
        {
            InitializeComponent();
        }

        private void btnCatchingExceptionThrownInAMethod_Click(object sender, EventArgs e)
        {
            try
            {
                Method1();
            }
            catch (DivideByZeroException de)
            {
                richTextBox1.Text = String.Format("Exception: {0} \n Caught in the button handler", de.GetType());
            }
        }
        private void Method1()
        {
            //try
            //{
                Method2(-5);
            //}
            //catch (DivideByZeroException de)
            //{
            //    richTextBox1.Text = String.Format("Exception: {0} \n Caught in Method1", de.GetType());
            //}
        }
        private void Method2(int n)
        {
            //try
            //{

                if (n < 0)
                    throw new DivideByZeroException("Attempt to divide by zero \n");
            //}
            //catch (DivideByZeroException de)
            //{
            //    richTextBox1.Text = String.Format("Exception: {0} \n Caught in Method2", de.GetType());
            //}
        }

        //=======================================================================================================
        private void btnTaskExceptionHandling_Click(object sender, EventArgs e)
        {
            //Run it from outside visual studio

            Task task1 = Task.Factory.StartNew(() =>
            {
                //Let this task throw an exception
                throw new DivideByZeroException("Cannot divide by zero");
            });
            try
            {
                task1.Wait();
            }
            catch (AggregateException ae) //We use this only when we need to catch task.Wait
            {
                foreach (Exception ex in ae.InnerExceptions)
                {
                    richTextBox1.AppendText(String.Format("Exception: {0} \n Aggregation Exception Caught", ex.GetType()));
                }
            }
        }
    }
}
//http://ozcode-orchard.azurewebsites.net/the-beginner%E2%80%99s-guide-to-exception-handling-with-the-tpl

No comments:

Post a Comment