0

Is this the correct way to check if an exception is a checked exception at runtime?

public boolean isChecked(final Throwable e) {
    return !(RuntimeException.class.isAssignableFrom(e.getClass()) 
             || Error.class.isAssignableFrom(e.getClass()));
}
ernest_k
  • 44,416
  • 5
  • 53
  • 99
  • 4
    `e instanceof RuntimeException`? – Steyrix Jan 20 '20 at 14:24
  • 2
    Can you add some context to your question? Perhaps the bigger question is whether or not you should be checking the exception, regardless of whether it be checked or unchecked. – Tim Biegeleisen Jan 20 '20 at 14:25
  • What do you need this for? – Thorbjørn Ravn Andersen Jan 20 '20 at 14:27
  • I have a very odd compile time error that forces me handle a thrown `Exception` but not a thrown `SomeSubClassOfException` that is not a runtime exception. Its a part of a small personal tutorial code that i am writing to revisit exception handling in java –  Jan 20 '20 at 14:42
  • 1
    Sounds like an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem/66378#66378). If you have a method declared with `throws Exception` or `throws Throwable`, change it to only throw exceptions it needs to throw. Note that multiple specific exceptions are allowed in a `throws` clause. – VGR Jan 20 '20 at 14:53
  • It was an XY Problem, I took a break then got back to it and figured it out. I am not posting the context because it is useless but, ill leave the question because there is none like it. –  Jan 20 '20 at 22:37

1 Answers1

2

I guess some condition like below will be enough

return !(e instanceof RuntimeException || e instanceof Error);
Steyrix
  • 2,796
  • 1
  • 9
  • 23
  • 4
    No need to guess: your condition is correct according to the Java Language Specification. *"The checked exception classes are all exception classes other than the unchecked exception classes. That is, the checked exception classes are Throwable and all its subclasses other than RuntimeException and its subclasses and Error and its subclasses."* https://docs.oracle.com/javase/specs/jls/se8/html/jls-11.html#jls-11.1.1 – kaya3 Jan 20 '20 at 14:30
  • @kaya3 thank you for clarifying. I had slight doubts about hierarchy and `Error`, but now it is clear – Steyrix Jan 20 '20 at 14:33
  • oh, i forgot about the 'instanceof' keyword. –  Jan 20 '20 at 14:43
  • @Sero well, if my answer helped you at some point, you can accept it, so the question will be closed :) – Steyrix Jan 20 '20 at 14:51