
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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)
Advertisements