Commonly asked Data Structures and Algorithms Problems by big tech and different solution approaches with code in Java and C

Powered by Blogger.

Saturday, February 29, 2020

Debug using exception.getCause()


While dealing with MultiThreading environment , we use Future so that we can get the result of the thread.
Future.get() throws  InterruptedException, ExecutionException and TimeoutException.

Suppose when thread gets called and during its execution something bad happened and raised a exception. So at that point of time it will stop executing and returns back to the caller.

And while retrieving from Futures, we get exception and most of the times we used to print the Exception Message but mostly it is not sufficeint to get the cause of the exception.

So either we need to configure our logs such that it prints StackTrace of the exception and its cause or while writing the code by using

1.  e.getStackTrace() which prints the stackTrace of the log
2.  e.getCause() which will give us the exception which was occurred while execution of the thread.

EXAMPLE :

try {
    future.get(TIMEOUT, TimeUnit.MILLISECONDS);}  
catch (final TimeoutException e) {
    log.info("time out while collecting constraint violation from thread:- ", e);
} catch (final Exception e) {
  log.error("exception while collecting constraint violation from thread:", e.getCause());
}



Note / More Info :

While a Exception chain is generated , it used to assign the cause of its downstream exception (because of this exception current one is being generated) which we find out by using e.getCause() but sometimes this cause is not being set so in this case it will result in giving null value. 


My View on it :

We can't always use e.getCause() because whenever a exception is created it's cause needs to be assigned.

And as per the definition , the reason may be unknown sometime and in this case it will print "null" and that would make things harder as log will print like "exception while collecting constraint violation from thread:- null" .

So either we can change our log configuration so that it also print stackTrace of Cause along with the exception, maybe we can reduce number of lines to be printed as some of the lines shows details of Future , Exception that we really don't care about

0 Comments:

Post a Comment

Stats