purpose of printStackTrace

printStackTrace() in Exception class, displays stack of details, from where(File name, class name and line number) the exception has been thrown, and further the methods/classes it has been propagated, and where it has been final caught. Click here to read output of printStackTrace into a String

Below is an example on how to use printStackTrace()

class CException
{
	public void testC() throws ArithmeticException,Exception
	{
		DException de = new DException();
		de.testD();
	}
}

class DException
{
	public void testD() throws ArithmeticException,Exception
	{
		int i,j=25,k=5;
			System.out.println("stmt 1");

			i = j/k;

			if(true)
			{
				throw new Exception("SampleException");
			}
			System.out.println("stmt 2");

	}
}

public class SimpleExcp {

	public static void main(String[] args){
		try
		{
			new CException().testC();

			try //nested try block
			{
				throw new Exception("TestingException");
			}
			catch(Exception te)
			{
				te.printStackTrace();
			}
		}
		catch(ArithmeticException ae)
		{
			System.out.println("--------AExcp:"+ae.getMessage());
			ae.printStackTrace();
		}
		catch(Exception et)
		{
			System.out.println("--------Excp:"+et.getMessage());
			et.printStackTrace();
		}
		finally
		{
			System.out.println("in finally block");
		}


	}

}


_______________________________________________________
Output:
——–Excp:SampleException
in finally block
java.lang.Exception: SampleException
at DException.testD(SimpleExcp.java:21)
at CException.testC(SimpleExcp.java:6)
at SimpleExcp.main(SimpleExcp.java:33)

3 thoughts on “purpose of printStackTrace”

Leave a Reply