Python: Catch Exception and Print

In this article, let us see how to catch an exception and print it instead of letting our programs crash with an error!

For those of you in a hurry here is the short version of the answer.

Short Version of the Answer

We can catch and print an exception by using the try-except block. For example, this line of code ends with an error.

print ("a" + 1)

OUTPUT

  File "main.py", line 1, in <module>
    print ("a" + 1)
TypeError: can only concatenate str (not "int") to str

But if we use try-except block we can catch the error and print our own message instead:

try:
    print ("a" + 1)
except:
    print("Oops, that was an error!")

OUTPUT

Oops, that was an error! 

The try part contains the code that might cause an error while the except part contains the alternate code that gets executed only when the try part has caused an error during execution.

Don’t worry if the above answer does not make sense to you as that was targeted at more experienced programmers who just wanted to refresh their memories. The rest of this article is dedicated to those of you in their first steps of their journey to become a Python Craftsman.

By the time you reach the end of this article, I suggest you come back and read this summary once more, I assure you it will make much more sense then!

Also if you are a visual learner, here is a youtube video we made on this very topic!

Mastering Exceptions in Python

I remember the time when I first came across an Exception in Python, as a beginner I was writing more English instead of Python and I expected the code to work the way I wanted to. In other words I was expecting the python interpreter to read my thoughts!

When the code crashed with a huge wall of text, I was overwhelmed and did not know what to do next! If you are in a similar situation and you wish to master the topic of Exceptions in python, I suggest you take out 20mins and read the article below.

Exceptions in Python: Everything You Need To Know!

If you are already familiar with exceptions and you are interested in mastering how to read the huge wall of text that comes with an Exception, here is an excellent article for you.

Python: Details contained in an Exception

There we have also explained how to print individual parts of the error text.

If all you are interested in is to just print a custom message out so that you can debug your code better then read on!

Catching Exceptions and Printing: A Thorough Answer

Python provides a very handy feature called try-block to help developers handle, or deal with exceptions.

You can keep the code that you suspect might cause an error in the try block and keep an alternate code in the except block.

Now

  • If your code does not cause an error, the try block code will complete its execution and except block will be skipped.
  • If the code inside the try block breaks at some point, the except block get executed.


Have a look at the following code:

a = 1
b = 2

print(c)

OUTPUT:

  File "main.py", line 4, in <module>
    print(c)
NameError: name 'c' is not defined

We see that a NameError exception was raised since I didn’t define anything called ‘c

Let’s do the same thing, but with try-block this time:

a = 1
b = 2

try:
    print(c)
except:
    print("There is no variable defined as c")

OUTPUT:

There is no variable defined as c

Since we kept a code that we suspected in the try block. As soon as the python interpreter saw an error, the execution of the try block was stopped and the except block started executing.

And now you have successfully caught the error and printed it. It’s as simple as that!

Let’s look at another example, this time a more complicated one.

Our goal is to

  • take two numbers from the user,
  • then divide them and print the result to the user.

We can do this using the following 4 lines of code.

a = int(input("Please enter your first number: "))
b = int(input("Please enter your second number: "))
c = a/b
print(str(a),"divided by",str(b),"is equal to", str(c))

This small 4-line program can actually crash under 2 different scenarios

  • The first situation is when the user tries to divide a number by zero, and
  • the second situation is when the input from the user is not a number itself

We can handle these errors using try-except blocks as follows

try:
  a = int(input("Please enter your first number: "))
  b = int(input("Please enter your second number: "))
  c = a/b
  print(str(a),"divided by",str(b),"is equal to", str(c))
    
except ZeroDivisionError as zde:
    print("The second number cannot be 0 as dividing by 0 is not allowed! Please try again")
    
except ValueError as ve:
    print("You did not enter a number! Please try again")

If this example feels too complicated to you, I strongly suggest you take out 20mins and read the article below.

Exceptions in Python: Everything You Need To Know!

Where to print the exception?

The 2 most popular locations to catch and print the exceptions are

  • the standard output/command line
  • a log file

Catching and Printing Exception to Standard Output/Command line

There are situations where it is useful to print an exception to the standard output. For example, you are going through the development process and you want immediate feedback on the screen then standard output/command line is the best option in your case.

To do this, you don’t need to do anything special or different, just use the same code in the example above and you can print stuff out to the standard output.

Catching and Printing Exception to a File

There are also situations where it is more useful to print the errors to a file instead of just the standard output. For example, consider the situation you have finished the development process and you have given your script to a friend/client who is not so tech-savvy, and he complains that your script has crashed without giving any detail as to what the error was.

In order to debug your code in such situations you can print the exception to a text file and exit the program. Then you can always retrieve the error messages through the files stored on the disk on your friend’s computer.

To catch and print an exception to a file, you can use a similar try-except block as before, but instead of using the print statement to output the exception, you can use the write method of a file object to write the exception to a file. Here’s an example of how you might do this:

PROGRAM:

try:
    number = int(input("Enter a number: "))
except ValueError as e:
    with open('exceptions.log', 'a') as myFile:
        myFile.write(str(e))

This will produce a file named exceptions.log on your computer, which you can open and read using any text editor as shown below.

In the above example, the exception is first converted to a string using the str function, and then it is written to a file called “exceptions.log” using the write method of the file object “myFile”. This file can then be shared with someone else, who can use it to help debug the program!

Here is the recipe/template used in the example above.

try:
    # code that might throw an exception goes here
except Exception as e:
    # code to handle the exception goes here
    with open('exceptions.log', 'a') as myFile:
        myFile.write(str(e))

Advanced: Using the Logging Class in Python:

If you want to take your exception printing to the next level, you might consider using the logging class in Python. The logging class is a useful tool that allows you to log messages to different destinations, such as the standard output, a file, or even a network socket.

Setting up the logging class is easy if you are fine with the defaults. You can do so with the following 2 lines of code:

import logging
logging.basicConfig(
    format='%(asctime)s %(levelname)-8s %(message)s',
    level=logging.DEBUG,
    datefmt='%Y-%m-%d %H:%M:%S')

Now depending on the severity of the error, you can print several levels of messages as shown below.

logging.warning('Watch out user!')
logging.debug('Some important debug information for me to use later')
logging.error('Cannot recover from this error, so lets log this important info and exit the program!')

This will produce output as follows.

Output

2023-01-03 01:11:01 WARNING  Watch out user!
2023-01-03 01:11:05 DEBUG    Some important debug information for me to use later
2023-01-03 01:11:10 ERROR    Cannot recover from this error, so lets log this important info and exit the program!

As you can see there are timestamps, type of message, and the message itself. This is what professional log files look like.

Explaining how to use the logger class is way beyond the scope of this article, my intention was to show you the capabilities of the logger class to pique your interest about the possibilities!

If you wish to learn more here is the official page of the logging class!

Summary

We can catch an exception using the try-except block and print it using the print function placed inside the except block.

try:
  #code that might cause an error

except:
  #code to run if an error is caught
  print("some simple error message")

Then while debugging, you keep the code that you suspect might cause an error in the try block and run your program.

  • If your code does not cause an error, the try block code will complete its execution and except block will be skipped.
  • If the code inside the try block breaks at some point, the except block get executed.

And with that I will end this article.

I hope you enjoyed reading this article and found it useful!

Feel free to share it with your friends and colleagues!

If your thirst for knowledge have not been quenched yet, here are some related articles that might spark your interest!

Related Articles

Exceptions in Python: Everything You Need To Know!

Python: Details contained in an Exception

Print just the message of an exception

Python: Print StackTrace on Exception!

Python: Printing Exception Type

Thanks to Namazi Jamal for his contributions in writing this article!

Photo of author
Editor
Balaji Gunasekaran
Balaji Gunasekaran is a Senior Software Engineer with a Master of Science degree in Mechatronics and a bachelor’s degree in Electrical and Electronics Engineering. He loves to write about tech and has written more than 300 articles. He has also published the book “Cracking the Embedded Software Engineering Interview”. You can follow him on LinkedIn