0

How do I know all the exceptions that an object can throw in Java? For example, Scanner.

3 Answers3

1

This is not exactly straightforward. Javadocs can help sometimes if the object methods have @throws in the javadoc comment that are accurate and up-to-date. If you have access to the code for the class, you could grep through for any throw statements to see what is directly thrown. But for most classes, the Exceptions that will be thrown will originate from objects used by the class, and not the class itself. For your example of Scanner, it will likely be a low-level IO primitive that will be throwing exceptions, and not methods of Scanner itself.

wmorrell
  • 4,988
  • 4
  • 27
  • 37
0

Will just add to others answers. Yes the Javadocs will be a good source, but there's no way to have a thorough list of all exceptions that will be thrown by such objects. Keep in mind that RuntimeExceptions and their subclasses are also possible at any point in the flow of the code and these do not have to be declared in the throws clause.

If you want to be cautious when calling a method, you can wrap the call in a try-catch and catch Exception. If you want to be as thorough as possible, you could try catching Throwable, but this is not advised. See: Is it a bad practice to catch Throwable?

Community
  • 1
  • 1
Kon
  • 10,702
  • 6
  • 41
  • 58
0

No. There is no definitive table. The classes included in the Java run-time environment are usually document in the individual Javadoc of the class you're interested in (e.g. Scanner). But Java isn't a closed ecosystem, and many applications include third party libraries (of varying quality documentation).

In the more general sense, if it's a checked Exception the compiler (or IDE) will tell you if you don't handle it. If it's an unchecked Exception it may or may not be documented.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249