Roshan Rathod
Can multiple catch blocks be executed?
By Roshan Rathod in C# on Oct 04 2020
  • Sachin Singh
    Oct, 2020 20

    No if any catch block gets executed it simply means compilar has found the exception then he will never go to the next one.Compilar will only execute the catch block which comes first and is appropriate.

    • 4
  • Varun Setia
    Oct, 2020 14

    No, once it enters catch block it will not enter again.

    • 2
  • shashi shekhar
    Dec, 2020 11

    No, multiple catch blocks cannot be executed. Once first catch block is catched, it will not read the next block.

    • 0
  • Kiran Mohanty
    Oct, 2020 6

    Yes we can define multiple catch blocks. The only condition we have to keep in mind is, we should define all derived class exceptions catch block first and then base class exception.

    For example, NullReferenceException is derived from Exception class. So we should define NullReferenceException catch block first and then Exception catch block. Reverse order will give compilation error as NullReferenceException catch block will never execute in that order.

    Here is the code for it.

    1. static void Main()
    2. {
    3. try{
    4. Console.WriteLine("start");
    5. throw new NullReferenceException();
    6. }
    7. catch(IndexOutOfRangeException ex){
    8. Console.WriteLine("out of range exception");
    9. Console.WriteLine("cause: "+ ex.Message);
    10. }
    11. catch(NullReferenceException ex){
    12. Console.WriteLine("null reference exception");
    13. Console.WriteLine("cause: "+ ex.Message);
    14. }
    15. catch(Exception ex){
    16. Console.WriteLine(ex.Message);
    17. }
    18. }

    • 0


Most Popular Job Functions


MOST LIKED QUESTIONS