Python

Python 3 Print Exception Message With Examples

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.

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.

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.

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.

Without using the sys package

The codes above use the sys package. Alternatively, we could show the Exception message in Python this way.

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.

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.

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like