0

I faced a question on Custom Exceptions in an Interview. As below there are four multiple catches which catch each custom exception. Interviewer asked me to write a pseudo code for catch blocks how i can handle all four custom exceptions.

enter image description here

I answered as

        try 
        {   try 
            {
                try { }
                catch (DEx dEx) { Console.WriteLine(dEx.Message); }
            }
            catch (BEx bEx) { Console.WriteLine(bEx.Message); }
            catch (CEx cEx) { Console.WriteLine(cEx.Message); }
        }
        catch (AEx aEx) { Console.WriteLine(aEx.Message); }  

Is it correct or wrong?

venkat
  • 5,648
  • 16
  • 58
  • 83

1 Answers1

1

CEx and DEx inherits for BEx and BEx inherits from AEx. So exception hanlding should start from bottom to up. Base exception last.

try
    {
       // statements causing exception
    }
    catch( CEx cEx )
    {
       // error handling for CEx
    }
    catch( DEx dEx )
    {
       // error handling for DEx
    }
    catch( BEx bEx )
    {
       // error handling for BEx
    }
    catch( AEx aEx )
    {
       // error handling for AEx
    }
    finally
    {
       // statements to be executed
    }
CharithJ
  • 46,289
  • 20
  • 116
  • 131
  • I answered for the above question in the interview as `try { try { try { } catch (DEx d) { Console.WriteLine(d.Message); } } catch (BEx b) { Console.WriteLine(b.Message); } catch (CEx c) { Console.WriteLine(c.Message); } } catch (AEx a) { Console.WriteLine(a.Message); }` – venkat Apr 25 '13 at 04:04
  • DEx and CEx(any order) should handle before BEx and then AEx. – CharithJ Apr 25 '13 at 04:05
  • Please see my updated question. I given my answer which i told at the time of interview – venkat Apr 25 '13 at 04:08
  • Sorry, I don't think it's correct. But the good thing is that you have realized that DEx should be the first one and AEx should be the last one to be handle. Obviously it doesn't require multiple try statements. – CharithJ Apr 25 '13 at 04:13
  • I was really confused and stunned when they asked me `Explain inheritance in Custom Exception Handling?` – venkat Apr 25 '13 at 04:15
  • All custom exceptions inherit from Exception base class. According to your image. AEx inherits from Exception class and BEx inherits from AEx. CEx and DEx inherits from BEx. – CharithJ Apr 25 '13 at 04:21