Aug 12, 2012

multiple catch statement with single try c#

Yes. Multiple catch blocks may be put in a try block. See code example below, to see multiple catch blocks being used in C#.


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Trycatch
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            int y = 0;
            int val;
            try
            {
                val = 100 / y;
                MessageBox.Show("Line not executed");
            }
            
            catch (ArgumentOutOfRangeException ex)
            {
                MessageBox.Show("Outof range exception");
            }
            catch (DivideByZeroException ex)
            {
                MessageBox.Show("DivideByZeroException");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Some Exception");
            }
            finally
            {
            MessageBox.Show("This Finally Line gets executed always");
            }

            }
                    }
                }



The catch Block
You can use a single catch block to handle all exceptions that may be generated in the try block, or you can use separate catch blocks each of which handles a particular type of exception.

Single catch Block
Use a single try...catch statement's catch block (recovery block) to execute error-handling code for any exceptions thrown in the try block.

No comments:

Post a Comment