Search code examples
javaexceptionchecked-exceptionsunchecked-exception

How to know if my code is using a checked or an unchecked exception?


Are there any keywords or special syntax of code that if I look at it, I'll know that here unchecked exception is being used or a checked exception is being used?

From reading previous posts that asked this question before, it seems to me that the only way to know if it's a check or unchecked is to see if the exception is extending Exception or RuntimeException.

Is that really the only way to know? Because I thought the syntax for writting unchecked and checked exceptions were supposed to be different too, but I'm not sure what to look for.


Solution

  • From Java document. it says "The class Exception and any subclasses that are not also subclasses of RuntimeException are checked exceptions." So your answer is Yes. But remember Error is also one type of unchecked exceptions.

    Checked exceptions need to be declared in a method or constructor's throws clause if they can be thrown by the execution of the method or constructor and propagate outside the method or constructor boundary.From You can use "isInstance()" function in Java to see if a specific exception belongs to a certain class. In your case, it would be if an exception is a RuntimeException. If yes, it is unchecked, if no, checked.

    You can also look for "java.lang.Object.getClass()" which can tell you the exact runtime class of the object.

    The other way I can think about handle them separately. You can catch RuntimeException and Error, then catch all other exceptions which are not the instances of RuntimeException.