title: Java: Write a generic method that throws any RuntimeException
body: <p>I am writing a method that basically does one simple thing, log the error message and throw a runtime exception using the same error message. I want it to be able to throw any child exception of RuntimeException. The method I have got is:</p>
  
  <pre><code>public static &lt;T extends RuntimeException&gt; void logErrorAndThrowException(Logger logger, String errorMessage, Class&lt;T&gt; exceptionClazz) throws T {
          logger.error(errorMessage);
          RuntimeException runtimeException = new RuntimeException(errorMessage);
          throw exceptionClazz.cast(runtimeException);   // Not work!!
      }
  </code></pre>
  
  <p>I have have this exception defined:</p>
  
  <pre><code>public final class MyException extends RuntimeException {
      public MyException() {
      }
  
      public MyException(String message) {
          super(message);
      }
  
      public MyException(Throwable cause) {
          super(cause);
      }
  
      public MyException(String message, Throwable cause) {
          super(message, cause);
      }
  }
  </code></pre>
  
  <p>I then invoke the method using:</p>
  
  <pre><code>   logErrorAndThrowException(logger, "This is an error message", MyException.class);
  </code></pre>
  
  <p>The commented line above will fail with an cast exception. I then tried another implementation of:</p>
  
  <pre><code>public static &lt;T extends RuntimeException&gt; void logWarningAndThrowException(Logger logger, String errorMessage, Class&lt;T&gt; exceptionClazz) throws T {
      logger.error(errorMessage);
      try {
          throw exceptionClazz.newInstance();
      } catch (InstantiationException e) {
          // handle
      } catch (IllegalAccessException e) {
          // handle
      }
  }
  </code></pre>
  
  <p>With this implementation, I can only invoke the no-arg constructor of my exception hence cannot set the error message.</p>
  
  <p>Can anyone help with this?</p>