Following snippet converts the exception or a throwable stack trace to string representation.
public static String throwableToString(Throwable t) {
	try (StringWriter stringWriter = new StringWriter(); PrintWriter pw = new PrintWriter(stringWriter, true);) {
		t.printStackTrace(pw);
		pw.flush();
		return stringWriter.toString();
	} catch (IOException e) {
		e.printStackTrace(System.err);
		return "Error occurred : " + e.getMessage();
	}
}
Find the below working application.
ThrowableToString.java
package com.sample.app.strings;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
public class ThrowableToString {
	public static String throwableToString(Throwable t) {
		try (StringWriter stringWriter = new StringWriter(); PrintWriter pw = new PrintWriter(stringWriter, true);) {
			t.printStackTrace(pw);
			pw.flush();
			return stringWriter.toString();
		} catch (IOException e) {
			e.printStackTrace(System.err);
			return "Error occurred : " + e.getMessage();
		}
	}
	public static void main(String[] args) {
		try {
			int result = 10 / 0;
			System.out.println(result);
		} catch (Throwable t) {
			System.out.println(throwableToString(t));
		}
	}
}
Output
java.lang.ArithmeticException: / by zero at com.sample.app.strings.ThrowableToString.main(ThrowableToString.java:23)
Previous Next Home

No comments:
Post a Comment