在采访中,面试官问我这个问题。 我们可以捕获基类中子类方法抛出的异常吗? 我说不,但他说是的,这是可能的。 所以我想知道这是否可能,如果是,请给我任何实际的例子。 你不必调用基类方法。 谢谢。
答案 0 :(得分:9)
这是一个简单的例子,其中基类从派生类中捕获异常。
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();
}
}
答案 1 :(得分:2)
你走了:
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
时,基类的实例会捕获另一个子类实例中抛出的异常。