KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
The above block refering to another question+answer on SO does NOT contain a correct answer which applies here! 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. /// <summary> /// Checks to make sure that the action throws a exception of type TException. /// </summary> /// <typeparam name="TException">The type of exception expected.</typeparam> /// <param name="action">The code to execute which is expected to generate the exception.</param> public static void Throws<TException>(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."); } The next call should succeed, but it fails: int result = 0; Throws<DivideByZeroException>(() => result = result / result); When the expected exception of type TException is thrown, it is always caught by the second catch, not by the first catch. Why is this? Of course I can use a workarround with one catch and test if ex is of type TException . By I simply want to know/understand why this code compiles but simple (never?) works. EDIT At request a "working" demo: using System; namespace GenericExceptionDemo { class Program { static void Main(string[] args)
Tags (comma-separated)
Save Edits
Cancel