Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an effective way to use generics in a throws clause?

Tags:

java

generics

According to Cannot Create, Catch, or Throw Objects of Parameterized Types (Java Tutorials):

You can, however, use a type parameter in a throws clause:

class Parser<T extends Exception> {
    public void parse(File file) throws T {     // OK
        // ...
    }
}

But why would you want to? You can't construct T here. If you inject T after building it outside, isn't its stack trace going to be all wrong? Were they simply documenting a feature that happened to work regardless of it's usefulness?

like image 487
candied_orange Avatar asked Jan 30 '26 03:01

candied_orange


1 Answers

Why not

class FooParser extends Parser<FooException> {
    public void parse(File file) throws FooException {
        throw new FooException("Not Supported");
    }
}
like image 170
David Ehrmann Avatar answered Feb 01 '26 15:02

David Ehrmann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!