Can we catch exception from child class method in base class in C#? -
in interview interviewer asked me question. can catch exception thrown child class method in base class? said no, said yes it's possible. want know possible @ , if yes please give me practical example. don't have call base class method. thanks.
here go:
public class baseclass { public void somemethod() { try { someothermethod(); } catch(exception ex) { console.writeline("caught exception: " + ex.message); } } public virtual void someothermethod() { console.writeline("i can overridden"); } } public class childclass : baseclass { public override void someothermethod() { throw new exception("oh no!"); } }
somemethod
, defined on base class, calls method someothermethod
of same object , catches exceptions. if override someothermethod
in child class , throws exception, caught in somemethod
defined on base class. language used in question little ambiguous (technically @ runtime still instance of childclass
doing exception handling) assume interviewer getting at.
another possibility (again, depending on interpretation) instance of base class calls method of different object inherits said base class, throws exception (and catches exception):
public class baseclass { public void somemethod() { var thing = new childclass(); try { thing.throwmyexception(); } catch(exception ex) { console.writeline("exception caught: " + ex.message); } } } public class childclass : baseclass { public void throwmyexception() { throw new exception("oh no!"); } }
here, when baseclass.somemethod
called, instance of base class catches exception thrown in another instance of child class.
Comments
Post a Comment