Note that there are some explanatory texts on larger screens.

plurals
  1. POIs a generic exception supported inside a catch?
    text
    copied!<p><strong>The above block refering to another question+answer on SO does NOT contain a correct answer which applies here!</strong></p> <p>I have a method used for unit testing. The purpose of this method is to ensure that a piece of code (refered to by a delegate) will throw a specific exception. If that exception is thrown, the unit test succeeds. If no exception is thrown or another type exception is thrown, the unit test will fail.</p> <pre><code>/// &lt;summary&gt; /// Checks to make sure that the action throws a exception of type TException. /// &lt;/summary&gt; /// &lt;typeparam name="TException"&gt;The type of exception expected.&lt;/typeparam&gt; /// &lt;param name="action"&gt;The code to execute which is expected to generate the exception.&lt;/param&gt; public static void Throws&lt;TException&gt;(Action action) where TException : Exception { try { action(); } catch (TException) { return; } catch (Exception ex) { Assert.Fail("Wrong exception was thrown. Exception of type " + ex.GetType() + " was thrown, exception of type " + typeof(TException) + " was expected."); } Assert.Fail("No exception was thrown. Exception of type " + typeof(TException) + " was expected."); } </code></pre> <p>The next call should succeed, but it fails:</p> <pre><code>int result = 0; Throws&lt;DivideByZeroException&gt;(() =&gt; result = result / result); </code></pre> <p>When the expected exception of type <code>TException</code> is thrown, it is always caught by the second catch, not by the first catch. Why is this? </p> <p>Of course I can use a workarround with one catch and test if <code>ex</code> is of type <code>TException</code>. By I simply want to know/understand why this code compiles but simple (never?) works.</p> <p><strong>EDIT</strong></p> <p>At request a "working" demo:</p> <pre><code>using System; namespace GenericExceptionDemo { class Program { static void Main(string[] args) { int n = 0; Catch&lt;DivideByZeroException&gt;(() =&gt; n = n / n); } static public void Catch&lt;TException&gt;(Action action) where TException: Exception { try { action(); Console.WriteLine("No exception thrown. !!!Fail!!!"); } catch (TException) { Console.WriteLine("Expected exception thrown. PASS!"); } catch(Exception ex) { Console.WriteLine("An unexpected exception of type " + ex.GetType() + " thrown. !!!FAIL!!!"); } } } } </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