Dec 21

Sometimes you need to store the stack trace from an exception in a String. A common approach is to use the printStackTrace() method to write it to a String which gives it to you in the same format as when you print it to stdout (or whereever)

StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
ex.printStackTrace(pw);
String trace = sw.toString();

Another option is to use the stack trace directly to create your string. This allows you to have full control over the format. For example you could use something as simple as the following:

String trace = Arrays.toString(ex.getStackTrace());

written by objects \\ tags: , , , ,

Oct 13

The StackTraceElement class can be used to get details about the call stack.

The following example shows how it can be used to view the call stack and determine where a method was called from.


public class WhoCalledMe
{

	public static void main(String[] args)
	{
		f();
	}
	
	public static void f()
	{
		g();
	}
	
	public static void g()
	{
		showCallStack();
		System.out.println();
		System.out.println(
			"g() was called by "+whoCalledMe());
	}

	public static String whoCalledMe()
	{
		StackTraceElement[] stackTraceElements = 
			Thread.currentThread().getStackTrace();
		StackTraceElement caller = stackTraceElements[4];
	    String classname = caller.getClassName();
	    String methodName = caller.getMethodName();
	    int lineNumber = caller.getLineNumber();
		return classname+"."+methodName+":"+lineNumber;
	}

	public static void showCallStack()
	{
		StackTraceElement[] stackTraceElements = 
			Thread.currentThread().getStackTrace();
		for (int i=2 ; i<stackTraceElements.length; i++)
		{
			StackTraceElement ste = stackTraceElements[i];
		    String classname = ste.getClassName();
		    String methodName = ste.getMethodName();
		    int lineNumber = ste.getLineNumber();
		    System.out.println(
		    	classname+"."+methodName+":"+lineNumber);
		} 
	}
}

written by objects \\ tags: , ,