printStackTrace in java

It prints the short description of the exception(using toString()) + a stack trace for this exception on the error output stream(System.err).

Constructors

  • public void printStackTrace()
  • public void printStackTrace(PrintStream s)
  • public void printStackTrace(PrintWriter s)

Example: printStackTrace()

public class Main {
 
    public static void main(String[] args) {
       int num1= 35, num2 = 0; 
 
	try { 
		int result = num1 / num2; 
	} 
	catch (ArithmeticException e) { 
		e.printStackTrace(); 
	} 
    }
}

Output:

java.lang.ArithmeticException: / by zero 
        at Main.main(Main.java:8)

Example: printStackTrace(PrintStream s)

import java.io.*;
 
public class Main {
 
    public static void main(String[] args) {
       int num1= 55, num2 = 0; 
 
	try { 
		int result = num1 / num2; 
	} 
	catch (ArithmeticException e) {
                PrintStream printStream = new PrintStream(System.out); 
                e.printStackTrace(printStream);
	} 
    }
}

Output:

java.lang.ArithmeticException: / by zero 
        at Main.main(Main.java:8)

Example: printStackTrace(PrintWriter s)

import java.io.*;
 
public class Main {
 
    public static void main(String[] args) {
       int num1= 15, num2 = 0; 
 
	try { 
		int result = num1 / num2; 
	} 
	catch (ArithmeticException e) {
            StringWriter stringWriter = new StringWriter(); 
            PrintWriter printWriter = new PrintWriter(stringWriter); 
            e.printStackTrace(printWriter);
            String stackTrace = stringWriter.toString(); 
            System.out.println("Exception Stack Trace:\n" + stackTrace); 
	} 
    }
}

Output:

Exception Stack Trace: 
java.lang.ArithmeticException: / by zero 
        at Main.main(Main.java:9)

Java interview questions on Exception Handling

Please Share