开发者

Catching somebody else's exception

开发者 https://www.devze.com 2023-01-06 05:42 出处:网络
We have a third party java code which is throwing a headless exception. Can we catch it in our code? The problem is how do we know which all third party code (which comes in a jar file) will throw the

We have a third party java code which is throwing a headless exception. Can we catch it in our code? The problem is how do we know which all third party code (which comes in a jar file) will throw the exception. We do not have 开发者_如何学Gothe third party API docs.


You can definitely catch it in your code by wrapping these third party calls inside a try/catch block.

As far as knowing the exception type without documentation, that's tougher. Trial and error by printing out the exception type during development. Or develop in very tight try/catch blocks that catch an open Exception.


Well,

In an ideal scenario, you should stop using that third party API. Since you are already using it, it would be much better if you write wrappers around and use it.

  • Construct an intermediate layer
  • Define custom exceptions clearly
  • Try analyzing the third party API main methods and see vulnerable points where you feel exceptions can arise
  • Promptly throw them wherever possible


I'm not clear what you mean by a headless exception.

The challenge is that if you don't know what methods could have exceptions, you would have to catch every time you call that third-party API. You may want to have some abstraction layer over that API that merely delegates and wraps every call with a try{call()} catch(Exception e){...}


Are you talking about java.awt.HeadlessException? According to the documentation:

Thrown when code that is dependent on a keyboard, display, or mouse is called in an environment that does not support a keyboard, display, or mouse.

Ofcourse you can try to catch it, but how it that going to help you? That third-party library probably won't be able to work on for example a server that doesn't have a keyboard, display or mouse.

0

精彩评论

暂无评论...
验证码 换一张
取 消