Important Notice: Our web hosting provider recently started charging us for additional visits, which was unexpected. In response, we're seeking donations. Depending on the situation, we may explore different monetization options for our Community and Expert Contributors. It's crucial to provide more returns for their expertise and offer more Expert Validated Answers or AI Validated Answers. Learn more about our hosting issue here.

We can declare methods that throw an exception (or error) of unknown type. Example (of method with type parameter in throws clause): interface Task< E extends Exception > { void run() throws E ; } Can such a method throw an object of the unknown exception (or error) type?

0
Posted

We can declare methods that throw an exception (or error) of unknown type. Example (of method with type parameter in throws clause): interface Task< E extends Exception > { void run() throws E ; } Can such a method throw an object of the unknown exception (or error) type?

0

• create a new exception (or error) and throw it • catch the exception (or error) of an invoked operation and re-throw it • propagate the exception (or error) of an invoked operation As we must not create objects of an unknown type the first possibility is not an option. Since type parameters must not appear in catch clauses, we cannot catch and therefore not re-throw an exception of an unknown type. At best, we can propagate an exception of unknown type that is raised by any of the invoked operations. Example (throwing an object of unknown type): final class CleanUp< E extends Exception , T extends Task> { public void cleanup(T task) throws E { task.run(); } } final class DisconnectTask implements Task { public void run() throws IllegalAccessException { … throw new IllegalAccessException(); … } } class Test { public static void main(String[] args) { CleanUp cleaner = new CleanUp

Related Questions

Experts123