- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Different ways to print exception messages in Java
Following are the different ways to handle exception messages in Java.
Using printStackTrace() method − It print the name of the exception, description and complete stack trace including the line where exception occurred.
catch(Exception e) { e.printStackTrace(); }
Using toString() method − It prints the name and description of the exception.
catch(Exception e) { System.out.println(e.toString()); }
Using getMessage() method − Mostly used. It prints the description of the exception.
catch(Exception e) { System.out.println(e.getMessage()); }
Example
import java.io.Serializable; public class Tester implements Serializable, Cloneable { public static void main(String args[]) { try { int a = 0; int b = 10; int result = b/a; System.out.println(result); } catch(Exception e) { System.out.println("toString(): " + e.toString()); System.out.println("getMessage(): " + e.getMessage()); System.out.println("StackTrace: "); e.printStackTrace(); } } }
Output
toString(): java.lang.ArithmeticException: / by zero getMessage(): / by zero StackTrace: java.lang.ArithmeticException: / by zero at Tester.main(Tester.java:8)
- Related Articles
- What are the different ways to print an exception message in java?
- How to print exception messages in android?
- Print system time in C++ (3 different ways)
- Different ways to concatenate Strings in Java
- Different ways to create Objects in Java
- Different messages in Tkinter - Python
- 5 different ways to create objects in Java
- Different ways to overload a method in Java
- Different ways to create an object in java?
- Different ways to traverse an Array in Java?
- Different ways for Integer to String conversion in Java
- Different ways to format long with Java System.out.format
- Ways to print escape characters in C#
- Ways to print escape characters in python
- What are the different ways to iterate over an array in Java?

Advertisements