Different Ways to Print Exception Messages in Java

In Java, there are three methods to print exception information. All of them are present 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.

Methods to Print Exceptions in Java

There are three methods to print exception messages in Java. These are:

1. java.lang.Throwable.printStackTrace() method:

By using this method, we will get the name(e.g., java.lang.ArithmeticException) and description(e.g., / by zero) of an exception separated by a colon, and the stack trace (wherein the code, that exception has occurred) in the next line.

Syntax:

public void printStackTrace()

Java

// Java program to demonstrate // printStackTrace method public class Test < public static void main(String[] args) 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

Using this method will only get the name and description of an exception. Note that this method is overridden in the Throwable class.

Java

// Java program to demonstrate // toString method public class Test < public static void main(String[] args) int a = 20 / 0 ; catch (Exception e) < // toString method System.out.println(e.toString()); // System.out.println(e); Output
java.lang.ArithmeticException: / by zero

3. java.lang.Throwable.getMessage() method:

Using this method, we will only get a description of an exception.

Syntax:

public String getMessage()

Java

// Java program to demonstrate // getMessage method public class Test < public static void main(String[] args) 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
Gaurav Miglani Like Article -->

Please Login to comment.

Similar Reads

Comparison of Exception Handling in C++ and Java

Both languages use to try, catch and throw keywords for exception handling, and their meaning is also the same in both languages. Following are the differences between Java and C++ exception handling: Java C++ Only throwable objects can be thrown as exceptions.All types can be thrown as exceptions.We can catch Exception objects to catch all kinds o

4 min read Java | Exception Handling | Question 1

Predict the output of following Java program class Main < public static void main(String args[]) < try < throw 10; >catch(int e) < System.out.println("Got the Exception " + e); >> > (A) Got the Exception 10 (B) Got the Exception 0 (C) Compiler Error Answer: (C) Explanation: In Java only throwable objects (Throwable objects are instances

1 min read Java | Exception Handling | Question 2 1 min read Java | Exception Handling | Question 3

Output of following Java program? class Main < public static void main(String args[]) < int x = 0; int y = 10; int z = y/x; >> (A) Compiler Error (B) Compiles and runs fine (C) Compiles fine but throws ArithmeticException exception Answer: (C) Explanation: ArithmeticException is an unchecked exception, i.e., not checked by the compiler. So the pro

1 min read Java | Exception Handling | Question 4 1 min read Java | Exception Handling | Question 8 class Test < public static void main (String[] args) < try < int a = 0; System.out.println ("a = " + a); int b = 20 / a; System.out.println ("b = " + b); >catch(ArithmeticException e) < System.out.println ("Divide by zero error"); >finally < System.out.println ("inside the finally block"); >> > (A) Compile 1 min read Java | Exception Handling | Question 6 1 min read Java | Exception Handling | Question 7 1 min read Java | Exception Handling | Question 8 1 min read Exception Propagation in Java

Prerequisite : Exceptions in Java, Checked vs Unchecked Exceptions Exception propagation : An exception is first thrown from the top of the stack and if it is not caught, it drops down the call stack to the previous method. After a method throws an exception, the runtime system attempts to find something to handle it. The set of possible "something

3 min read Exception Handling with Method Overriding in Java

An Exception is an unwanted or unexpected event, which occurs during the execution of a program i.e at run-time, that disrupts the normal flow of the program’s instructions. Exception handling is used to handle runtime errors. It helps to maintain the normal flow of the program. In any object-oriented programming language, Overriding is a feature t

6 min read Java - Exception Handling With Constructors in Inheritance

Java provides a mechanism to handle exceptions. To learn about exception handling, you can refer to exceptions in java. In this article, we discuss exception handling with constructors when inheritance is involved. In Java, if the constructor of the parent class throws any checked exception, then the child class constructor can throw the same excep

7 min read User-defined Custom Exception in Java

An exception is an issue (run time error) that occurred during the execution of a program. When an exception occurred the program gets terminated abruptly and, the code past the line that generated the exception never gets executed. Java provides us the facility to create our own exceptions which are basically derived classes of Exception. Creating

3 min read Infinity or Exception in Java when divide by 0?

Consider the following code snippets: public class Geeksforgeeks < public static void main(String[] args) < double p = 1; System.out.println(p/0); >> Output: Infinity public class Geeksforgeeks < public static void main(String[] args) < int p = 1; System.out.println(p/0); >> Output: Exception in thread "main" java.lang.ArithmeticException: / by z

1 min read Array Index Out Of Bounds Exception in Java

Java supports the creation and manipulation of arrays as a data structure. The index of an array is an integer value that has value in the interval [0, n-1], where n is the size of the array. If a request for a negative or an index greater than or equal to the size of the array is made, then the JAVA throws an ArrayIndexOutOfBounds Exception. This

4 min read Types of Exception in Java with Examples

Java defines several types of exceptions that relate to its various class libraries. Java also allows users to define their own exceptions. Built-in Exceptions: Built-in exceptions are the exceptions that are available in Java libraries. These exceptions are suitable to explain certain error situations. Below is the list of important built-in excep

8 min read Output of Java program | Set 12(Exception Handling)

Prerequisites : Exception handling , control flow in try-catch-finally 1) What is the output of the following program? public class Test < public static void main(String[] args) < try < System.out.printf("1"); int sum = 9 / 0; System.out.printf("2"); >catch(ArithmeticException e) < System.out.printf("3"); >catch(Exce

3 min read Understanding OutOfMemoryError Exception in Java

In Java, all objects are stored in a heap. They are allocated using a new operator. The OutOfMemoryError Exception in Java looks like this: Exception in thread "main" java.lang.OutOfMemoryError: Java heap space Usually, this error is thrown when the Java Virtual Machine cannot allocate an object because it is out of memory. No more memory could be

9 min read Null Pointer Exception In Java

NullPointerException is a RuntimeException. In Java, a special null value can be assigned to an object reference. NullPointerException is thrown when a program attempts to use an object reference that has the null value. Reason for Null Pointer ExceptionThese are certain reasons for Null Pointer Exception as mentioned below: Invoking a method from

6 min read Nested try blocks in Exception Handling in Java

In Java , we can use a try block within a try block. Each time a try statement is entered, the context of that exception is pushed onto a stack. Given below is an example of a nested try. In this example, the inner try block (or try-block2) is used to handle ArithmeticException, i.e., division by zero. After that, the outer try block (or try-block)

3 min read How to Create Different Packages For Different Classes in Java?

Let us first know what is a class and package in Java. Class in java is a model for creating objects. It means that the properties and actions of the objects are written in class. Properties are represented by variables and actions of the objects are represented by methods. So, a class contains variables and methods. The same variables are also ava

6 min read Different ways for String to Integer Conversions in Java

Given a String in Java, the task is to convert this String into Integer. Examples: Input: str = "1234" Output: 1234 Input: str = "456" Output: 456 Convert using Integer.parseInt(String) The Integer class has a static method that returns an integer object representing the specified String parameter. Syntax : public static int parseInt(String str) th

2 min read Different Ways to Remove all the Digits from String in Java

Given alphanumeric string str, the task is to write a Java program to remove all the digit from this string and prints the modified string. Examples: Input: str = “GeeksForGeeks123”Output: GeeksForGeeksExplanation: The given string contains digits 1, 2, and 3. We remove all the digit and prints the modified string. Input: str = “12Java”Output: Java

3 min read Different Ways to Generate String by using Characters and Numbers in Java

Given a number num and String str, the task is to generate the new String by extracting the character from the string by using the index value of numbers. Examples: Input: str = “GeeksforGeeks” num = 858 Output: GfG Explanation: The 8th, 5th, and 8th position of the characters are extracting from the given string and generate a new string. Input: s

3 min read Different Ways To Check Java Version In Windows

Java is a programming language that is platform-independent, popular, simple, secure, and statically typed. Before discussing let's clear Java language needs a runtime platform so before going ahead let's clear how java is present on the machine. Java language comprises three components mainly: Java Development KitJava Runtime EnvironmentJava Virtu

3 min read Different Ways to Achieve Pass By Reference in Java

There are two types of parameters one is Formal parameters and the second is Actual Parameters. Formal parameters are those parameters that are defined during function definition and Actual parameters are those which are passed during the function call in other Function. Showcasing the formal and actual parameters through code: Java Code // Java pr

5 min read Different Ways To Declare And Initialize 2-D Array in Java

An array with more than one dimension is known as a multi-dimensional array. The most commonly used multi-dimensional arrays are 2-D and 3-D arrays. We can say that any higher dimensional array is basically an array of arrays. A very common example of a 2D Array is Chess Board. A chessboard is a grid containing 64 1x1 square boxes. You can similarl

8 min read Different Ways to Prevent Method Overriding in Java

Inheritance is a substantial rule of any Object-Oriented Programming (OOP) language but still, there are ways to prevent method overriding in child classes which are as follows: Methods: Using a static methodUsing private access modifierUsing default access modifierUsing the final keyword method Method 1: Using a static method This is the first way

5 min read Different Ways to Create the Instances of Wrapper Classes in Java

Wrapper Class a class whose object wraps or contains primitive data types. When we create an object to a wrapper class, it contains a field and in this field, we can store primitive data types. In other words, we can wrap a primitive value into a wrapper class object. Methods: We can use two ways to construct the instance of the Wrapper Classes Usi

5 min read Different Ways to Copy Files in Java

There are mainly 3 ways to copy files using java language. They are as given below: Using File Stream (Naive method)Using FileChannel ClassUsing Files class. Note: There are many other methods like Apache Commons IO FileUtils but we are solely discussing copying files using java classes. Method 1: Using File Stream (Naive method) This is a naive me