This post shows how to print the message and details of an Exception in Python. Sometimes, when we encounter errors, the messages aren’t clear or misleading. Also, the details may be lacking. We used Python 3.7.0 for this post.
Catch Specific Exception And Show The Message Or Details
Python has a try-catch feature to enable programmers’ code to handle errors elegantly. It has a different name for it, though. We can call it try-except in Python. All the codes that may cause errors we place in the try block. Meanwhile, we handle the errors in the except block. Finally, we have the else block that always runs.
1 2 3 4 5 6 7 8 9 10 11 12 13 | import sys def main(): try: x = int('Not a number') except ValueError as error: print(f'Exception Message -> {sys.exc_info()[1]}') print(f'Details -> {sys.exc_info()}') else: print('No error') if __name__ == "__main__": main() |
When we run the codes, we get the following output. The first line shows the error message, while the second line prints out more details about the error.
1 2 | Exception Message -> invalid literal for int() with base 10: 'Not a number' Details -> (<class 'ValueError'>, ValueError("invalid literal for int() with base 10: 'Not a number'"), <traceback object at 0x04F1F8C8>) |
Catch-All Exception
Sometimes we want to catch any error because we cannot anticipate all the possible errors our Python program may encounter. To catch all errors, we don’t specify the type of error in the except clause. Consider the following Python codes.
1 2 3 4 5 6 7 8 9 10 11 12 13 | import sys def main(): try: x = int('Not a number') except: print(f'Unknown Error - {sys.exc_info()[1]}') print(f'Details - {sys.exc_info()}') else: print('No error') if __name__ == "__main__": main() |
In this scenario, we need to use Python’s sys pack because out except clause has no clue about the errors it catches. The codes generate the following output.
1 2 | Unknown Error - invalid literal for int() with base 10: 'Not a number' Details - (<class 'ValueError'>, ValueError("invalid literal for int() with base 10: 'Not a number'"), <traceback object at 0x04BBF800>) |
Without using the sys package
The codes above use the sys package. Alternatively, we could show the Exception message in Python this way.
1 2 3 4 5 6 7 8 9 10 | def main(): try: x = int('Not a number') except Exception as e: print(f'Unknown Error - {e}') else: print('No error') if __name__ == "__main__": main() |
When we don’t use the sys package, the only way to catch all errors is utilizing the Exception in the except clause. If we run the codes without using the mentioned package, we’ll get a similar result.
1 | Unknown Error - invalid literal for int() with base 10: 'Not a number' |
Using the sys package offers more options to programmers. For instance, we can display the details of the error. Otherwise, we only get the error messages which are sometimes not as detailed as we hope for.
And that’s how we can print exception messages and details in Python.