- In Java there are three ways to find the details of the exception .
- They are
- Using an object of java.lang.Exception
- Using public void printStackTrace() method
- Using public String getMessage() method.
1.Using an object of java.lang.Exception
- An object of Exception class prints the name of the exception and nature of the exception.
Write a Java program get detailed message details using exception class object
- package exceptions;
- public class ExceptionDetails {
- /**
- * @www.instanceofjava.com
- **/
- public static void main(String[] args) {
- try {
- int x=1/0;
- } catch (Exception e) {
- System.out.println(e);
- }
- }
- }
Output:
- java.lang.ArithmeticException: / by zero
2.Using public void printStackTrace() method
- This is the method which is defined in java.lang.Throwable class and it is inherited into java.lang.Error class and java.lang.Exception class
- This method will display the name of the exception and nature of the message and line number where exception has occurred.
Write a simple java example program to print exception message to console using printStacktrace() method
- package exceptions;
- public class ExceptionDetails {
- /**
- * @www.instanceofjava.com
- */
- public static void main(String[] args) {
- try {
- int a[]= new int[1];
- a[1]=12
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
Output:
- java.lang.ArrayIndexOutOfBoundsException: 1
at exceptions.ExceptionDetails.main(ExceptionDetails.java:13)
3.Using public String getMessage() method
- This is also a method which is defined in java.lang.Throwable class and it is inherited in to both java.lanf.Error and java.lang.Exception classes.
- This method will display the only exception message
Write a Java program print exception message using getMessage() method.
- package exceptions;
- public class ExceptionDetails {
- /**
- * @www.instanceofjava.com
- */
- public static void main(String[] args) {
- try {
- int x=1/0;
- } catch (Exception e) {
- System.out.println(e.getMessage());
- }
- }
- }
Output:
- / by zero
Bagikan
3 different ways to print exception message in java
4/
5
Oleh
Kris Kimcil