3

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?

Community
  • 1
  • 1
candied_orange
  • 7,036
  • 2
  • 28
  • 62

3 Answers3

3

Why not

class FooParser extends Parser<FooException> {
    public void parse(File file) throws FooException {
        throw new FooException("Not Supported");
    }
}
David Ehrmann
  • 7,366
  • 2
  • 31
  • 40
1

You could have

public class ExceptionWithPayload<T> extends Exception {
    private final T payload;
    public ExceptionWithPayload(T payload) {
        this.payload = payload;
    }
    public T getPayload(){
        return payload;
    }
}

and then in some other class, you could write

throw new ExceptionWithPayload<MyClass>(myObject);

so as to be able to pass any object you like back to the thing that catches the exception, but with type checking in the catch clause.

Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110
  • This doesn't work, it is showing a compile time error `Generic class may not extend Throwable` – Pratik Singhal Mar 14 '19 at 07:54
  • That could happen if you've made your own class called `Exception`. Don't do that. – Dawood ibn Kareem Mar 14 '19 at 08:11
  • Nope, I was trying to extend RuntimeException. – Pratik Singhal Mar 14 '19 at 09:13
  • I suggest you ask a new question and post your code. Link to this one if you like. – Dawood ibn Kareem Mar 14 '19 at 09:23
  • I don't think posting a separate question would help here. It would be good, if you could review and correct the answer. – Pratik Singhal Mar 14 '19 at 09:35
  • The OP accepted this answer which means it worked for that person. If you're doing something different then you have a new question. I'm not going to change my answer to fit your requirement. It's correct as it is. – Dawood ibn Kareem Mar 14 '19 at 09:37
  • I am not doing something different. This answer is clearly wrong. OP accepting it at that time, doesn't mean it's correct now. I am not asking you to delete the answer , just verify it and add a comment, if it doesn't work. Checkout the following answer https://stackoverflow.com/a/501284/2790036 – Pratik Singhal Mar 14 '19 at 09:46
1

You can throw checked exceptions where it was not expected with the sneaky throw trick: http://rdafbn.blogspot.hu/2013/07/lomboks-sneaky-throws.html

Or without magic: http://www.mail-archive.com/javaposse@googlegroups.com/msg05984.html

Gábor Bakos
  • 8,982
  • 52
  • 35
  • 52