Search code examples
javaexceptionthrow

Java exception handling: catch an exception thrown by an external dependency module


I am calling from within a module A a class from a module B (which is just a dependency I can't modify): inside the class of the module B is been thrown a NullPointerException. I would need to catch this NullPointerException in the point where I'm calling this module B class.

Please note that the NullPointerException does not come out run time, but is explicitly thrown with a "throw"

Theoretically speaking, would I be able to do that?


Solution

  • Java does not know about modules or whether you can modify them, so this works as usual:

    If a statement throws an exception, it will be delivered to the first matching catch block of a caller. Therefore, if module B does not catch the exception, it will arrive at your catch block.