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.
No, once it enters catch block it will not enter again.
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.
static void Main() { try{ Console.WriteLine("start"); throw new NullReferenceException(); } catch(IndexOutOfRangeException ex){ Console.WriteLine("out of range exception"); Console.WriteLine("cause: "+ ex.Message); } catch(NullReferenceException ex){ Console.WriteLine("null reference exception"); Console.WriteLine("cause: "+ ex.Message); } catch(Exception ex){ Console.WriteLine(ex.Message); } }
static void Main()
{
try{
Console.WriteLine("start");
throw new NullReferenceException();
}
catch(IndexOutOfRangeException ex){
Console.WriteLine("out of range exception");
Console.WriteLine("cause: "+ ex.Message);
catch(NullReferenceException ex){
Console.WriteLine("null reference exception");
catch(Exception ex){
Console.WriteLine(ex.Message);
No, multiple catch blocks cannot be executed. Once first catch block is catched, it will not read the next block.