Print Exception Stack Trace Details Java

Usually when exception occurs in java program it easy to print full stack details on the console. If you are using logger to log exception message and want to see details exception trace you will have to fetch it from stack trace. Below program will show you how to fetch full details of exception from stack trace:

  • ExceptionTrace.java
/**
 * @author javahonk
 * 
 */
public class PrintExceptionTrace {
	
	public static void main(String args[]) {
		
		//Generate exception
		try {
			Integer value = 1/0;			
			System.out.println(value);
			
		} catch (Exception e) {
			System.out.println(getExceptionStackTrace(e));
		}
		
	}

	public static String getExceptionStackTrace(Exception exception) {
		StringWriter writer = new StringWriter();
		PrintWriter printWriter = new PrintWriter(writer);
		exception.printStackTrace(printWriter);
		printWriter.flush();
		return writer.toString();
	}

}
  • Output:

Print Exception Stack Trace Details Java

  • Read more about java here

Leave a Reply

Your email address will not be published. Required fields are marked *