Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<pre><code>class MyClass { public virtual void Foo() { if (true) throw new System.Exception(); } } } class MyDerivedClass : MyClass { public override void Foo() { if (true) throw new ArgumentNullException(); } } } public class Program { public static void Main() { try { // a factory creating the correct // MyClass derived instance var myClass = someFactory.Create(); myClass.Foo(); } catch (Exception) { // will work. } } } </code></pre> <p>In this case you are throwing the least specific exception possible in the base class (why that sucks is another discussion). As in such, anyone using the sub classes will be able to catch that, no matter how specific exception you throw.</p> <hr> <p>Let's say that it had been the other way around. The base class throws <code>ArgumentNullException</code> and the sub class <code>Exception</code>. Now, anyone only knowing about the base class would only have catch blocks for <code>ArgumentNullException</code> as that is what they expect. Their application will therefore fail when the sub class throws <code>Exception</code>.</p> <pre><code>class MyClass { public virtual void Foo() { if (true) throw new ArgumentNullException(); } } } class MyDerivedClass : MyClass { public override void Foo() { if (true) throw new Exception(); } } } public class Program { public static void Main() { try { // a factory creating the correct // MyClass derived instance var myClass = someFactory.Create(); myClass.Foo(); } catch (ArgumentNullException) { // won't work since the subclass // violates LSP } } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload