Monday 25 January 2016

Multiple catch block in exception in C# with example?

Can we have multiple catch block in exception? We can have multiple catch for a try block. But we can not have (Exception ex1) on top because it catches all exception as super type. Never when one catch block is executed, controls skip all other catch blocks and goes to finally block. Wrong: - try { -------- } catch (Exception ex2) { -------- } catch (DivideByZeroException ex1) { ---------- } finally { ------------- } Error 1 A previous catch clause already catches all exceptions of this or of a super type ('System.Exception') E:\C# Examples\Multiple Catch Block Exception\Multiple Catch Block Exception\Program.cs 26 20 Multiple Catch Block Exception Right :- try { -------- } catch (DivideByZeroException ex1) { } catch (Exception ex2) { } finally {}




using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Multiple_Catch_Block_Exception
{
  
    //Run this program and type 0 (that is numeric) and 'a' (that is char) on the console to check both catch blocks in action.
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                int numerator = 10;
                int denominator = GetText();
                int result = numerator / denominator;
            }
            catch (DivideByZeroException ex1)
            {
                string msg = ex1.Message.ToString();
                Console.WriteLine(msg + " I'm from 1st catch block");
            }
            catch (Exception ex2)
            {
                string msg = ex2.Message.ToString();
                Console.WriteLine(msg + " I'm from 2nd catch block");
            }
            finally
            {
                Console.WriteLine("In finally block.");
            }
            Console.ReadKey();
        }
 
        private static int GetText()
        {
            string x = Console.ReadLine();
            return Convert.ToInt32(x);
        }
    }
 
}
  

  
 
sdf