Is it possible to throw an exception from a method of a child class in a base class in C #?

In an interview, the interviewer asked me this question. Can we catch the exception thrown by the method of the child class in the base class? I said no, but he said it was possible. So I want to know if this is possible at all, and if so, please give me some practical example. You do not need to call the base class method. Thank you

+4
source share
2 answers

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, , SomeOtherMethod . SomeOtherMethod - , SomeMethod, . , , ( ChildClass, ), , , .

( , ) , , , ( ):

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!");
    }
}

, BaseClass.SomeMethod, , .

+2

, .

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();
    }
}
+8

Source: https://habr.com/ru/post/1546346/


All Articles