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
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.
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.
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.
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.
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"] }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With