Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get detail messages of chained exceptions Java

I'd like to know how I could throw a "final" Exception, containing a detailed message with all the detailed messages of a number of chained exceptions.

For example suppose a code like this:

try {   try {     try {       try {         //Some error here       } catch (Exception e) {         throw new Exception("FIRST EXCEPTION", e);       }     } catch (Exception e) {       throw new Exception("SECOND EXCEPTION", e);     }   } catch (Exception e) {     throw new Exception("THIRD EXCEPTION", e);   } } catch (Exception e) {   String allMessages = //all the messages   throw new Exception(allMessages, e); } 

I'm not interested in the full stackTrace, but only in the messages, I wrote. I mean, I'd like to have a result like this:

java.lang.Exception: THIRD EXCEPTION + SECOND EXCEPTION + FIRST EXCEPTION 
like image 941
MikO Avatar asked Apr 13 '13 11:04

MikO


People also ask

How do I get Detailmessage from exception?

The getMessage() method of Throwable class is used to return a detailed message of the Throwable object which can also be null. One can use this method to get the detail message of exception as a string value. Return Value: This method returns the detailed message of this Throwable instance. // the getMessage() Method.

How do you handle exceptions in method chaining in Java?

Methods Of Throwable class Which support chained exceptions in java : getCause() method :- This method returns actual cause of an exception. initCause(Throwable cause) method :- This method sets the cause for the calling exception.

How do I read an exception message in Java?

Following are the different ways to handle exception messages in Java. Using printStackTrace() method − It print the name of the exception, description and complete stack trace including the line where exception occurred. Using toString() method − It prints the name and description of the exception.

What is chained exception in Java?

Chained Exception helps to identify a situation in which one exception causes another Exception in an application. For instance, consider a method which throws an ArithmeticException because of an attempt to divide by zero but the actual cause of exception was an I/O error which caused the divisor to be zero.


1 Answers

I think what you need is:

public static List<String> getExceptionMessageChain(Throwable throwable) {     List<String> result = new ArrayList<String>();     while (throwable != null) {         result.add(throwable.getMessage());         throwable = throwable.getCause();     }     return result; //["THIRD EXCEPTION", "SECOND EXCEPTION", "FIRST EXCEPTION"] } 
like image 171
卢声远 Shengyuan Lu Avatar answered Sep 26 '22 02:09

卢声远 Shengyuan Lu