Can we catch exception from child class method in base class in C#?

后端 未结 2 1385
[愿得一人]
[愿得一人] 2021-01-18 14:16

In an interview interviewer asked me this question. Can we catch exception thrown by a child class method in base class? I said no, but he said yes it\'s possible. So I w

2条回答
  •  深忆病人
    2021-01-18 14:31

    Here you 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 be overridden");
        }
    }
    
    public class ChildClass : BaseClass
    {
        public override void SomeOtherMethod()
        {
            throw new Exception("Oh no!");
        }
    }
    

    SomeMethod, defined on the base class, calls another method SomeOtherMethod of the same object and catches any exceptions. If you override SomeOtherMethod in some child class and it throws an exception, then this is caught in SomeMethod defined on the base class. The language used in your question is a little ambiguous (technically at runtime it is still the instance of ChildClass doing the exception handling) but I assume that this is what your interviewer was getting at.

    Another possibility (again, depending on the interpretation) is that an instance of a base class calls a method of a different object that inherits said base class, which throws an exception (and then catches the 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 is called, an instance of a base class catches an exception thrown in another instance of a child class.

提交回复
热议问题