Get detail messages of chained exceptions Java

后端 未结 5 570
面向向阳花
面向向阳花 2020-12-28 16:29

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

5条回答
  •  旧时难觅i
    2020-12-28 16:59

    Cycle through the exception cause and append the message in each exception.

        try
        {
            try
            {
                try
                {
                    try
                    {
                        throw new RuntimeException("Message");
                    }
                    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 message = e.getMessage();
            Throwable inner = null;
            Throwable root = e;
            while ((inner = root.getCause()) != null)
            {
                message += " " + inner.getMessage();
                root = inner;
            }
            System.out.println(message);
        }
    

    Which prints

    THIRD EXCEPTION SECOND EXCEPTION FIRST EXCEPTION Message

提交回复
热议问题