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

后端 未结 2 1409
[愿得一人]
[愿得一人] 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:24

    Here's a simple example in which a base class is catching an exception from a derived class.

    abstract class Base
    {
        // A "safe" version of the GetValue method.
        // It will never throw an exception, because of the try-catch.
        public bool TryGetValue(string key, out object value)
        {
            try
            {
                value = GetValue(key);
                return true;
            }
            catch (Exception e)
            {
                value = null;
                return false;
            }
        }
    
        // A potentially "unsafe" method that gets a value by key.
        // Derived classes can implement it such that it throws an
        // exception if the given key has no associated value.
        public abstract object GetValue(string key);
    }
    
    class Derived : Base
    {
        // The derived class could do something more interesting then this,
        // but the point here is that it might throw an exception for a given
        // key. In this case, we'll just always throw an exception.
        public override object GetValue(string key)
        {
            throw new Exception();
        }
    }
    

提交回复
热议问题