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!
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!