Print a message of the thrown exception to system error

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

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

public class Test {

    public static void main(String[] args)

    {

        try {

            int a = 20 / 0;

        }

        catch (Exception e) {

            e.printStackTrace();

            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

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

Java

public class Test {

    public static void main(String[] args)

    {

        try {

            int a = 20 / 0;

        }

        catch (Exception e) {

            System.out.println(e.toString());

        }

    }

}

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

public class Test {

    public static void main(String[] args)

    {

        try {

            int a = 20 / 0;

        }

        catch (Exception e) {

            System.out.println(e.getMessage());

        }

    }

}

This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

In this article, let us learn about printing error messages from Exceptions with the help of 5 specifically chosen examples.

I have divided this article into 2 major sections

  1. Printing custom error messages and
  2. Printing a specific part of the default error message. By “default error message“, I mean the error message that you typically get in the command line if you did not catch a given exception)

Depending on which of the 2 options above you are looking for, you can jump to the respective section of the article using the table of content below.

So, let’s begin!

Printing Custom Error messages

There are 3 ways to print custom error messages in Python. Let us start with the simplest of the 3, which is using a print() statement.

Option#1: Using a simple print() statement

The first and easiest option is to print error messages using a simple print() statement as shown in the example below.

try:
    #Some Problematic code that can produce Exceptions
    x = 5/0
except Exception as e:
  print('A problem has occurred from the Problematic code: ', e)

Running this code will give the output below.

A problem has occurred from the Problematic code: division by zero

Here the line “x = 5/0″ in Example 1 above raised a “ZeroDivisionError” which was caught by our except clause and the print() statement printed the default error message which is “division by zero” to the standard output.

One thing to note here is the line “except Exception as e“. This line of code’s function is to catch all possible exceptions, whichever occurs first as an “Exception” object. This object is stored in the variable “e” (line 4), which returns the string ‘division by zero‘ when used with the print() statement (line 5).

To summarize if you wish to print out the default error message along with a custom message use Option#1.

This is the simplest way to print error messages in python. But this option of putting your custom messages into print statements might not work in cases where you might be handling a list of exceptions using a single except clause. If you are not exactly sure how to catch a list of exceptions using a single except clause, I suggest reading my other article in the link below.

Python: 3 Ways to Catch Multiple Exceptions in a single “except” clause

There I have explained the 3 ways through which you can catch a list of exceptions along with tips on when is the right situation to catch each of these exceptions.

Now that we have learned how to print the default string which comes with an exception object, let us next learn how to customize the message that e carried (the string ‘division by zero‘) and replace that with our own custom error message.

Option#2: Using Custom Exception classes to get customized error messages

In Python, you can define your own custom exception classes by inheriting from another Exception class as shown in the code below.

class MyOwnException(Exception):
    def __str__(self):
        return 'My Own Exception has occurred'

    def __repr__(self):
        return str(type(self))
try:
    raise MyOwnException
except MyOwnException as e:
    print(e)
    print(repr(e))

How to choose the exception class to inherit from?

In the above example, I have inherited from the Exception class in python, but the recommended practice is to choose a class that closely resembles your use-case.

For example, say you are trying to work with a string type object and you are given a list type object instead, here you should inherit your custom exception from TypeError since this Exception type closely resembles your use case which is “the variable is not of expected type”.

If you are looking for getting an appropriate Exception class to inherit from, I recommend having a look at all the built-in exceptions from the official python page here. For the sake of keeping this example simple, I have chosen the higher-level exception type named “Exception” class to inherit from.

In the code below, we are collecting values from the user and to tell the user that there is an error in the value entered we are using the ValueError class.

class EnteredGarbageError(ValueError):
    def __str__(self):
        return 'You did not select an option provided!'    

try:
    options = ['A', 'B', 'C']
    x = input('Type A or B or C: ')
    if x not in options:
        raise EnteredGarbageError
    else:
        print ('You have chosen: ', x)

except EnteredGarbageError as err:
    print(err)

Now that we understand how to choose a class to inherit from, let us next have a look at how to customize the default error messages that these classes return.

How to customize the error message in our custom exception class?

To help us achieve our purpose here which is to print some custom error messages, all objects in python come with 2 methods named __str__ and __repr__. This is pronounced “dunder-str” and “dunder-repr” where “dunder” is short for “double underscore”.

Dunder-str method:

The method __str__ returns a string and this is what the built-in print() function calls whenever we pass it an object to print.

print(object1)

In the line above, python will call the __str__ method of the object and prints out the string returned by that method.

Let us have a look at what python’s official documentation over at python.org has to say about the str method.

https://docs.python.org/3/reference/datamodel.html#object.str

In simpler words, the str method returns a human-readable string for logging purposes, and when this information is passed to the built-in function print(), the string it returns gets printed.

So since our implementation of str returns the string “My Own Exception has occurred” this string got printed on the first line of the exception message.

Dunder-repr method:

__repr__ is another method available in all objects in python.

Where it differs from the dunder-str method is the fact that while the __str__ is used for getting a “friendly message”, the __repr__ method is used for getting, a more of a, “formal message”. You can think of str as a text you got from your friends and repr as a notice you got from a legal representative!

The below screenshot from python’s official documentation explains the use of __repr__ method.

https://docs.python.org/3/reference/datamodel.html#object.repr

Again, in simpler words, repr is typically used to print some “formal” or “official” information about an object in Python

In our Example 2 above, the repr method returned the class name using the built-in type() function.

Next, let us see another variation where we can print different error messages using a single Exception class without making a custom class.

Option#3: Custom Error messages from the raise statement

try:
  raise Exception('I wish to print this message')
except Exception as error:
  print(error)

Lucky for us, python has made this process incredibly simple! Just pass in the message as an argument to the type of exception you wish to raise and this will print that custom message instead!

In the above code, we are throwing an exception of type “Exception” by calling its constructor and giving the custom message as an argument, which then overrides the default __str__ method to return the string passed in.

If you wish to learn more about raise statement, I suggest reading my other article in the link below
Python: Manually throw/raise an Exception using the “raise” statement

where I have explained 3 ways you can use the raise statement in python and when to use each.

But when to use option 2 and when to use option 3?

On the surface, Option#3 of passing in the custom message may look like it made option#2 of using custom classes useless. But the main reason to use Option#2 is the fact that Option#2 can be used to override more than just the __str__ method.

Let’s next move on to section 2 of this article and look at how to choose a specific part of the default error message (the error printed on the console when you don’t catch an exception) and use that to make our own error messages

Choosing Parts of Default Error Messages to print

To understand what I mean by “Default Error Message” let us see an example

raise ValueError("This is an ValueError")

This line when run, will print the following error message

Traceback (most recent call last):

  File "<ipython-input-24-57127e33a735>", line 1, in <module>
    raise ValueError("This is an ValueError")

ValueError: This is an ValueError

This error message contains 3 Parts

  • Exception Type (ValueError)
  • Error message (This is an ValueError)
  • and the stack trace (the 1st few lines showing us where exactly in the program the exception has occurred)

The information needed

  • to extract and use each of the individual pieces of information listed above and
  • when to use what piece of information

is already covered with the help of several examples in my previous article in the link below

Python Exceptions: Getting and Handling Error Messages as strings.

And with that I will end this article!

If you are looking for another interesting read, try the article in the link below.

Exceptions in Python: Everything You Need To Know!

The above article covers all the basics of Exception handling in Python like

  • when and how to ignore exceptions
  • when and how to retry the problematic code that produced the exception and
  • when and how to log the errors

I hope you enjoyed reading this article and got some value from it.

Feel free to share it with your friends and colleagues!

An exception is an issue (run time error) 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.

Printing the Exception message

You can print the exception message in Java using one of the following methods which are inherited from Throwable class.

  • printStackTrace() − This method prints the backtrace to the standard error stream.
  • getMessage() − This method returns the detail message string of the current throwable object.
  • toString() − This message prints the short description of the current throwable object.

Example

import java.util.Scanner;
public class PrintingExceptionMessage {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter first number: ");
      int a = sc.nextInt();
      System.out.println("Enter second number: ");
      int b = sc.nextInt();
      try {
         int c = a/b;
         System.out.println("The result is: "+c);
      }catch(ArithmeticException e) {
         System.out.println("Output of printStackTrace() method: ");
         e.printStackTrace();
         System.out.println(" ");
         System.out.println("Output of getMessage() method: ");
         System.out.println(e.getMessage());
         System.out.println(" ");
         System.out.println("Output of toString() method: ");
         System.out.println(e.toString());
      }
   }
}

Output

Enter first number:
10
Enter second number:
0
Output of printStackTrace() method:
java.lang.ArithmeticException: / by zero

Output of getMessage() method:
/ by zero

Output of toString() method:
java.lang.ArithmeticException: / by zero
at PrintingExceptionMessage.main(PrintingExceptionMessage.java:11)

Printing the custom exception message

Re-throwing the exception — You can re-throw the exception catched in the catch block using new keyword, while doing this you need to pass the catched exception object along with a String representing a message, then the message you have passed is displayed instead of original message.

Example

import java.util.Scanner;
public class PrintingExceptionMessage {
   public static void main(String args[]) throws Exception {
      String msg = "This is my custom message";
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter first number: ");
      int a = sc.nextInt();
      System.out.println("Enter second number: ");
      int b = sc.nextInt();
      try {
         int c = a/b;
         System.out.println("The result is: "+c);
      }catch(ArithmeticException e) {
         throw new Exception("CoustomMessage: "+msg, e);
      }
   }
}

Output

Enter first number:
25
Enter second number:
0
Exception in thread "main" java.lang.Exception: CoustomMessage: This is my custom message
at july_set3.PrintingExceptionMessage.main(PrintingExceptionMessage.java:16)
Caused by: java.lang.ArithmeticException: / by zero
at july_set3.PrintingExceptionMessage.main(PrintingExceptionMessage.java:13)

Creating Custom Exception − You can create and re-throw a custom exception with desired message.

Example

import java.util.Scanner;
class MyException extends Exception{
   public MyException(String msg){
      super(msg);
   }
}
public class PrintingExceptionMessage {
   public static void main(String args[]) throws Exception {
      String msg = "This is my custom exception";
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter first number: ");
      int a = sc.nextInt();
      System.out.println("Enter second number: ");
      int b = sc.nextInt();
      try {
         int c = a/b;
         System.out.println("The result is: "+c);
      }catch(ArithmeticException e) {
         MyException exce = new MyException(msg);
         throw exce;
      }
   }
}

Output

Enter first number:
14
Enter second number:
0
Exception in thread "main" july_set3.MyException: This is my custom exception
   at july_set3.PrintingExceptionMessage.main(PrintingExceptionMessage.java:23)

3 different ways to print exception message in java


Posted by: InstanceOfJava


Posted date:

Apr 25, 2016



/

  • In Java there are three ways to find the details of the exception .
  • They are 
  1. Using an object of java.lang.Exception
  2. Using public void printStackTrace() method
  3. 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

  1. package exceptions;
  2. public class ExceptionDetails {
  3.  
  4. /**
  5.  * @www.instanceofjava.com
  6.  **/
  7.  public static void main(String[] args) {
  8.  
  9. try {
  10.  
  11. int x=1/0;
  12.             
  13. } catch (Exception e) {
  14.             System.out.println(e);
  15. }
  16.  
  17. }
  18.  
  19. }

 

Output:

  1. 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

  1. package exceptions;
  2. public class ExceptionDetails {
  3.  
  4.     /**
  5.      * @www.instanceofjava.com
  6.      */
  7. public static void main(String[] args) {
  8.  
  9.  try {
  10.           int a[]= new int[1];
  11.             a[1]=12
  12.             
  13. } catch (Exception e) {
  14.    e.printStackTrace();
  15.            
  16.  }
  17. }
  18.  
  19. }

 

Output:

  1. 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.

  1. package exceptions;
  2. public class ExceptionDetails {
  3.  
  4.     /**
  5.      * @www.instanceofjava.com
  6.      */
  7.     public static void main(String[] args) {
  8.  
  9.         try {
  10.             int x=1/0;
  11.             
  12.         } catch (Exception e) {
  13.             System.out.println(e.getMessage());
  14.         }
  15.     }
  16.  
  17. }

 

Output:

  1.  / by zero

print exception message

Tagged with:

exception handling interview questions


Instance Of Java

We will help you in learning.Please leave your comments and suggestions in comment section. if you any doubts please use search box provided right side. Search there for answers thank you.

Понравилась статья? Поделить с друзьями:
  • Prism3d engine ошибка как исправить
  • Prince of persia warrior within управление как исправить
  • Prism error verifying vbmeta image
  • Prince of persia warrior within игру невозможно запустить синтаксическая ошибка
  • Printservice error 372