<p>Right, I know I am totally going to look an idiot with this one, but my brain is just <em>not</em> kicking in to gear this morning.</p>
<p>I want to have a method where I can say &quot;if it goes bad, come back with this type of Exception&quot;, right?</p>
<p>For example, something like (<strong>and this doesn't work</strong>):</p>
<pre><code>    static ExType TestException&lt;ExType&gt;(string message) where ExType:Exception
    {
        Exception ex1 = new Exception();
        ExType ex = new Exception(message);
        return ex;
    }
</code></pre>
<p>Now whats confusing me is that we <em>KNOW</em> that the generic type is going to be of an Exception type due to the <em>where</em> clause. However, the code fails because we cannot implicitly cast <em>Exception</em> to <em>ExType</em>. We cannot explicitly convert it either, such as:</p>
<pre><code>    static ExType TestException&lt;ExType&gt;(string message) where ExType:Exception
    {
        Exception ex1 = new Exception();
        ExType ex = (ExType)(new Exception(message));
        return ex;
    }
</code></pre>
<p>As that fails too.. So <strong>is this kind of thing possible?</strong> I have a strong feeling its going to be real simple, but I am having a tough day with the old noggin, so cut me some slack :P</p>
<hr />
<h2>Update</h2>
<p>Thanks for the responses guys, looks like it wasn't me being a <em>complete</em> idiot! ;)</p>
<p>OK, so <a href="https://stackoverflow.com/questions/41397/asking-a-generic-method-to-throw-specific-exception-type-on-fail#41398">Vegard</a> and <a href="https://stackoverflow.com/questions/41397/asking-a-generic-method-to-throw-specific-exception-type-on-fail#41404">Sam</a> got me on to the point where I could instantiate the correct type, but then obviously got stuck because the <em>message</em> param is read-only following instantiation.</p>
<p><a href="https://stackoverflow.com/questions/41397/asking-a-generic-method-to-throw-specific-exception-type-on-fail#41408">Matt</a> hit the nail right on the head with his response, I have tested this and all works fine. Here is the example code:</p>
<pre><code>    static ExType TestException&lt;ExType&gt;(string message) where ExType:Exception, new ()
    {
        ExType ex = (ExType)Activator.CreateInstance(typeof(ExType), message);
        return ex;
    }
</code></pre>
<p>Sweet! :)</p>
<p>Thanks guys!</p>

[{'answer_id': 41402, 'author': 'Jon Limjap', 'author_id': 372, 'author_profile': 'https://Stackoverflow.com/users/372', 'pm_score': 0, 'selected': False, 'text': '<p>Have you tried, instead:</p>\n\n<pre><code>static T TestException&lt;Exception&gt;(string message)\n{}\n</code></pre>\n\n<p>because I have a feeling that putting in the generic constraint is not necessary as all throwable exceptions <em>must</em> inherit from System.Exception anyway.</p>\n\n<p>Remember that generics do accept inherited types.</p>\n'}, {'answer_id': 41404, 'author': 'samjudson', 'author_id': 1908, 'author_profile': 'https://Stackoverflow.com/users/1908', 'pm_score': -1, 'selected': False, 'text': "<p>I think seeing as all exceptions should have a parameterless constructor, and have the <code>Message</code> property, so the following should work:</p>\n\n<pre><code>static ExType TestException&lt;ExType&gt;(string message) where ExType:Exception\n{\n    ExType ex = new ExType();\n    ex.Message = message;\n    return ex;\n}\n</code></pre>\n\n<p>Edit: OK, Message is read only, so you'll have to hope the class implements the Exception(string) constructor instead.</p>\n\n<pre><code>static ExType TestException&lt;ExType&gt;(string message) where ExType:Exception\n{\n    return new ExType(message);\n}\n</code></pre>\n"}, {'answer_id': 41408, 'author': 'Matt Hamilton', 'author_id': 615, 'author_profile': 'https://Stackoverflow.com/users/615', 'pm_score': 6, 'selected': True, 'text': '<p>You can almost do it like this:</p>\n\n<pre><code>static void TestException&lt;E&gt;(string message) where E : Exception, new()\n{\n    var e = new E();\n    e.Message = message;\n    throw e;\n}\n</code></pre>\n\n<p>However, that doesn\'t compile because Exception.Message is read only. It can only be assigned by passing it to the constructor, and there\'s no way to constrain a generic type with something other than a default constructor.</p>\n\n<p>I think you\'d have to use reflection (Activator.CreateInstance) to "new up" the custom exception type with the message parameter, like this:</p>\n\n<pre><code>static void TestException&lt;E&gt;(string message) where E : Exception\n{\n    throw Activator.CreateInstance(typeof(E), message) as E;\n}\n</code></pre>\n\n<p><strong>Edit</strong> Oops just realised you\'re wanting to <em>return</em> the exception, not throw it. The same principle applies, so I\'ll leave my answer as-is with the throw statements.</p>\n'}, {'answer_id': 41450, 'author': 'samjudson', 'author_id': 1908, 'author_profile': 'https://Stackoverflow.com/users/1908', 'pm_score': 4, 'selected': False, 'text': '<p>The only issue with the solution is that it is possible to create a subclass of Exception which does not implement a constructor with a single string parameter, so the MethodMissingException might be thrown.</p>\n\n<pre><code>static void TestException&lt;E&gt;(string message) where E : Exception, new()\n{\n    try \n    {\n      return Activator.CreateInstance(typeof(E), message) as E;\n    } \n    catch(MissingMethodException ex) \n    {\n      return new E();\n    }\n}\n</code></pre>\n'}, {'answer_id': 9113952, 'author': 'MiloNC', 'author_id': 1185299, 'author_profile': 'https://Stackoverflow.com/users/1185299', 'pm_score': 1, 'selected': False, 'text': '<p>I have been instantiating inline the type of exception I want to throw, like this:</p>\n\n<pre><code>if (ItemNameIsValid(ItemName, out errorMessage))\n    throw new KeyNotFoundException("Invalid name \'" + ItemName + "\': " + errorMessage);\nif (null == MyArgument)\n    throw new ArgumentNullException("MyArgument is null");\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/41397', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/832/']