Java - find the first cause of an exception Java - find the first cause of an exception oracle oracle

Java - find the first cause of an exception


In the interests of not reinventing the wheel, if you're using Apache Commons Lang, then look at ExceptionUtils.getRootCause().

Is it worth including a library just for that? Maybe not. But if you already have it on your classpath, it's there for you, and note that it does some things that a 'naive' implementation might not do (e.g. deal with cycles in the cause chain... ugh!)


Just traverse the exception chain until you get to an exception with no cause, and then just return that message, if you want the last one.

Your function will only get the first cause, if there is one.

You may want to look at finding the first cause in your package though, as the actual deepest one may be an oracle exception, which is helpful, but unless you can see where you created the problem, you will have a hard time fixing it.