Print full exception python

How To Catch And Print The Exception Messages In Python

Sometimes, a Python script comes across an unusual situation that it can’t handle, and the program gets terminated or crashes. In this article, we’ll learn How to catch and print exception messages in Python which can help us better understand and debug such errors. If you want to learn more about Python Programming, visit Python Tutorials.

In Python, you can catch and print exception messages using “try-except” statements or “logger. exception()”. With the “try-except” approach, enclose the code in a try block, then use “except Exception as e” to catch the exception and save its message in variable e. Print it using “print(e)” or process it further.

Another method to catch and print an exception message in Python is by using logger.exception()” which provides an error message and trace information like line number and time.

The most common example of an exception is a “FileNotFoundError” which is raised when you’re importing a file, but it doesn’t exist. Similarly, dividing a number by zero gives a “ZeroDivisionError” and displays a system-generated error message. All these run-time errors are known as exceptions. These exceptions should be caught and reported to prevent the program from being terminated.

Читайте также:  Css problems in chrome

In Python, exceptions are handled with the (try… except) statement. The statements which handle the exceptions are placed in the except block whereas the try clause includes the expressions which can raise an exception. Consider an example in which you take a list of integers as input from the user.

# Creating an empty list new_list =[] n = int(input("Enter number of elements : ")) for i in range(n): item = int(input()) # Add the item in the list new_list.append(item) print(new_list)

The program shown above takes integers as input and creates a list of these integers. If the user enters any character, the program will crash and generate the following output.

OUTPUT: Enter number of elements : 7 23 45 34 65 2a --------------------------------------------------------------------------- ValueError Traceback (most recent call last) in () 3 n = int(input("Enter number of elements : ")) 4 for i in range(n): ----> 5 item = int(input()) 6 # Add the item in the list 7 new_list.append(item) ValueError: invalid literal for int() with base 10: '2a'

Use Except and Try statement to catch and print the Exception and save its Error Messages

The first method to catch and print the exception messages in Python is by using except and try statements. If the user enters anything except the integer, we want the program to skip that input and move to the next value. In this way, our program will not crash and will catch and print the exception message. This can be done using try and except statements. Inside the try clause, we’ll take input from the user and append it to “new_list” variable. If the user has entered any input except integers mistakenly, the except block will print “Invalid entry” and move towards the next value. In this way, the program continues to run and skip the invalid entries.

# Creating an empty list new_list =[] n = int(input("Enter number of elements : ")) for i in range(n): try: item = int(input()) # Add the item in the list new_list.append(item) except: print("Invalid Input!") print("Next entry.") print("The list entered by user is: ", new_list)
Enter number of elements : 7 65 43 23 4df Invalid Input! Next entry. 76 54 90 The list entered by user is: [65, 43, 23, 76, 54, 90]

There are various methods to catch and report these exceptions using try and except block. Some of them are listed below along with examples.

Catching and Reporting/Print exceptions messages in Python

This is the second method to catch and print the exception messages in Python. With the help of the print function, you can capture, get and print an exception message in Python. Consider an example in which you have a list containing elements of different data types. You want to divide all the integers by any number. This number on division with the string datatypes will raise “TypeError” and the program will terminate if the exceptions are not handled. The example shown below describes how to handle this problem by capturing the exception using the try-except block and reporting it using the print command.

EXAMPLE 1:

list_arr=[76,65,87,"5f","7k",78,69] for elem in list_arr: try: print("Result: ", elem/9) except Exception as e: print("Exception occurred for value '"+ elem + "': "+ repr(e))
Result: 8.444444444444445 Result: 7.222222222222222 Result: 9.666666666666666 Exception occurred for value '5f': TypeError("unsupported operand type(s) for /: 'str' and 'int'") Exception occurred for value '7k': TypeError("unsupported operand type(s) for /: 'str' and 'int'") Result: 8.666666666666666 Result: 7.666666666666667

Using try and logger.exception to print an Error message

Another method is to use logger.exception() which produces an error message as well as the log trace, which contains information such as the code line number at which the exception occurred and the time the exception occurred. This logger.exception() method should be included within the except statement; otherwise, it will not function properly.

import logging logger=logging.getLogger() num1=int(input("Enter the number 1:")) num2=int(input("Enter the number 2:")) try: print("Result: ", num1/num2) except Exception as e: logger.exception("Exception Occured while code Execution: "+ str(e))
Enter the number 1:82 Enter the number 2:4 Result: 20.5

Suppose a user enters 0 in the 2nd number, then this will raise a “ZeroDivisionError” as shown below.

Enter the number 1:9 Enter the number 2:0 Exception Occured while code Execution: division by zero Traceback (most recent call last): File "", line 11, in print("Result: ", num1/num2) ZeroDivisionError: division by zero

Similarly, if you’ve two lists consisting of integers and you want to create a list consisting of results obtained by dividing list1 with list2. Suppose you don’t know whether the two lists consist of integers or not.

EXAMPLE 2:

import logging logger=logging.getLogger() list1=[45, 32, 76, 43, 0, 76] list2=[24, "world", 5, 0, 4, 6] Result=[] for i in range(len(list1)): try: Result.append(list1[i]/list2[i]) except Exception as e: logger.exception("Exception Occured while code Execution: "+ str(e)) print(Result)

In this example, “world” in the 2nd index of list2 is a string and 32 on division with a string would raise an exception. But, we have handled this exception using try and except block. The logger.exception() command prints the error along with the line at which it occurred and then moves toward the next index. Similarly, all the values are computed and stored in another list which is then displayed at the end of the code.

 Exception Occured while code Execution: unsupported operand type(s) for /: 'int' and 'str' Traceback (most recent call last): File "", line 8, in Result.append(list1[i]/list2[i]) TypeError: unsupported operand type(s) for /: 'int' and 'str' Exception Occured while code Execution: division by zero Traceback (most recent call last): File "", line 8, in Result.append(list1[i]/list2[i]) ZeroDivisionError: division by zero [1.875, 15.2, 0.0, 12.666666666666666]

The logger module has another function “logger.error()” which returns only an error message. The following example demonstrates how the logger.error() function may be used to capture exception messages in Python. In this example, we have just replaced logger.exception in the above example with logger.error() function

EXAMPLE 3:

import logging logger=logging.getLogger() list1=[45, 32,76,43,0, 76] list2=[24, "world", 5, 0, 4, 6] Result=[] for i in range(len(list1)): try: Result.append(list1[i]/list2[i]) except Exception as e: logger.error("Exception Occured while code Execution: "+ str(e)) print(Result)
Exception Occured while code Execution: unsupported operand type(s) for /: 'int' and 'str' Exception Occured while code Execution: division by zero [1.875, 15.2, 0.0, 12.666666666666666]

Catching and printing Specific Exceptions messages

The previous section was all about how to catch and print exceptions. But, how will you catch a specific exception such as Valueerror, ZeroDivisionError, ImportError, etc? There are two cases if you want to catch one specific exception or multiple specific exceptions. The following example shows how to catch a specific exception.

EXAMPLE 4:

a = 'hello' b = 4 try: print(a + b) except TypeError as typo: print(typo)
can only concatenate str (not "int") to str

Similarly, if you want to print the result of “a/b” also and the user enters 0 as an input in variable “b”, then the same example would not be able to deal with ZeroDivisionError. Therefore we have to use multiple Except clauses as shown below.

EXAMPLE 5:

a = 6 b = 0 try: print(a + b) print(a/b) except TypeError as typo: print(typo) except ZeroDivisionError as zer: print(zer)

The same code is now able to handle multiple exceptions.

To summarize, all of the methods described above are effective and efficient. You may use any of the methods listed above to catch and print the exception messages in Python depending on your preferences and level of comfort with the method. If you’ve any queries regarding this article, please let us know in the comment section. Your feedback matters a lot to us.

Источник

Оцените статью