There are three methods to print exception information in Java. They are all in the Throwable class. Since Throwable is the base class for all exceptions and errors, we can use these three methods on any exception object.
Syntax:
public void printStackTrace()
// Java program to demonstrate // printStackTrace method public class Test { public static void main(String[] args) { try { int a = 20/0; } catch (Exception e) { // printStackTrace method // prints line numbers + call stack e.printStackTrace(); // Prints what exception has been thrown System.out.println(e); } } }
Runtime Exception:
java.lang.ArithmeticException: / by zero at Test.main(Test.java:9)
Output:
java.lang.ArithmeticException: / by zero
2. toString() method : With this method we only get the name and description of the exception. Note that this method has been overridden in the Throwable class.
// Java program to demonstrate // toString method public class Test { public static void main(String[] args) { try { int a = 20/0; } catch (Exception e) { // toString method System.out.println(e.toString()); // OR // System.out.println(e); } } }
Output:
java.lang.ArithmeticException: / by zero
3. java.lang.Throwable.getMessage() method : By using this method, we will only get description of an exception.
Syntax:
public String getMessage()
// Java program to demonstrate // getMessage method public class Test { public static void main(String[] args) { try { int a = 20/0; } catch (Exception e) { // getMessage method // Prints only the message of exception // and not the name of exception System.out.println(e.getMessage()); // Prints what exception has been thrown // System.out.println(e); } } }
Output:
/ by zero
Australia
UK
UAE
Singapore
Canada
New
Zealand
Malaysia
USA
India
South
Africa
Ireland
Saudi
Arab
Qatar
Kuwait
Hongkong
Copyright 2016-2023 www.programmingshark.com - All Rights Reserved.
Disclaimer : Any type of help and guidance service given by us is just for reference purpose. We never ask any of our clients to submit our solution guide as it is, anywhere.