Skip to content

Instantly share code, notes, and snippets.

@loxal
Last active July 21, 2016 11:36
Show Gist options
  • Save loxal/bd6b992c94ebe1d6a889 to your computer and use it in GitHub Desktop.
Save loxal/bd6b992c94ebe1d6a889 to your computer and use it in GitHub Desktop.
Interview: Generics and Type Reification
import java.sql.SQLException;
public class Mocker<T extends Exception> {
private void pleaseThrow(final Exception e) throws T {
throw (T) e;
}
public static void main(String[] args) {
try {
new Mocker<RuntimeException>().pleaseThrow(new SQLException());
} catch (final SQLException e) {
e.printStackTrace();
}
}
}
@loxal
Copy link
Author

loxal commented Aug 12, 2015

What happens with this Java code?

(1) Throws ClassCastException because SQLException is not instanceof RuntimeException
(2) Compilation fails because no SQLException is thrown
(3) The program prints the stacktrace of the newly thrown SQLException
(4) Compilation fails because we cannot cast SQLException to RuntimeException

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment