java - Direct Generic Exceptions -
my question follow-up question:
why doesn't java allow generic subclasses of throwable?
the question answered perfectly, on indirect generic exception, that's:
public class myexception<t> extends exception {
what left void, direct generics:
public static <t extends exception> void checkforexception(class<t> extype) { try { // code } catch (t e) { e.printstacktrace(); } }
why not allowed?
though, reason think not allowed, t
type, explicitly caught:
// if t ioexception catch(t e) { } catch(ioexception e) { }
but reason block it? same effect, done without generics too:
catch(exception e) { } catch(ioexception e { }
here's documentation of above restriction.
because in java type variables, i.e. t, not reifiable due type erasure.
this means compiler not have t @ runtime @ all.
hence there no way catch block of yours ever know t was. , no, can't treat base type. different. if had
catch(t e) { } catch(mybaseexception e) { } catch(myapplicationexception e) { }
and t extends mybaseexception. see how got bad quick?
read more in excellent java generics faqs - under hood of compiler
personally i've never liked type erasure, language designers swore had reasons using it. here are.
Comments
Post a Comment