Csharp/C#教程:我们可以在C#的基类中从子类方法中捕获exception吗?分享


我们可以在C#的基类中从子类方法中捕获exception吗?

在采访中,面试官问我这个问题。 我们可以捕获基类中子类方法抛出的exception吗? 我说不,但他说是的,这是可能的。 所以我想知道这是否可能,如果是,请给我任何实际的例子。 您不必调用基类方法。 谢谢。

干得好:

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并捕获任何exception。 如果在某个子类中重写SomeOtherMethod并抛出exception,则会在基类上定义的SomeMethod捕获此exception。 你的问题中使用的语言有点含糊不清(技术上在运行时它仍然是ChildClass做exception处理的实例)但我认为这是你的面试官得到的。

另一种可能性(同样,取决于解释)是基类的实例调用inheritance所述基类的不同对象的方法,该基类抛出exception(然后捕获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!"); } } 

这里,当调用BaseClass.SomeMethod时,基类的实例捕获在子类的另一个实例中抛出的exception。

这是一个简单的示例,其中基类从派生类中捕获exception。

上述就是C#学习教程:我们可以在C#的基类中从子类方法中捕获exception吗?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

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

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/951157.html

(0)
上一篇 2021年11月18日
下一篇 2021年11月18日

精彩推荐