views:

75

answers:

4

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 the third party API docs.

+1  A: 

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.

Jason McCreary
A: 

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
Bragboy
A: 

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){...}

Uri
A: 

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.

Jesper