A simple example of the try/except Python statements

There is so much confusion being created on the Internet geek communities when it comes to the try/except statements in the Python computer programming language, especially among the complete beginners who have no idea at all about error handling practices.

Having struggled myself with the try/except statements during the beginning of my Python coding journey, I decided to share a simple example which can be a benefit to a lot of people who are interested in learning the Python computer programming language. The sample code being shared through this tutorial, has not practical usage in real world scenarios, but for sure it is a great source to use when stuck in a try/except piece of Python code.

First of all, before progressing any further, anyone who is interested in the Python computer programming language and is reading this article, should know that there are two kinds of error:

What's the one thing every developer wants? More screens! Enhance your coding experience with an external monitor to increase screen real estate.

  • Syntax based errors
  • Exception based errors

The first ones in the above list, the syntax based errors, arise when the Python interpreter fails to interpret a line of code because of its wrong syntax. On the other hand, the exception based errors occur during the execution time in the Python interpreter.

For a beginner in the Python computer programming language, I recommend they run the following piece of code in their interactive Python console.

1/0

Once the above Python code is being executed in the interactive Python shell, the following error is being displayed. It is an exception being thrown in the interactive console.

Traceback (most recent call last):
File “”, line 1, in
1/0
ZeroDivisionError: integer division or modulo by zero

The experienced Python coder, can easily notice the exception thrown in the above piece of Python code. Based on my experience with the Python computer programming language, one can make use of the try/except block to handle exceptions like the one which is thrown in the example shown above.

The code for simply handling exceptions in Python is being shown below.


try:
1/0
except ZeroDivisionError:
print('You can not divide by 0')

Once the above code is being executed in the Python interactive shell, no exception will be thrown. This time it is being handled, and a nice custom message will be displayed to the user.

Final thoughts

The above example is a very simple one, being shared with the main purpose of giving a basic idea to the Python beginners on error and exception handling in Python.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Leave a Reply

Your email address will not be published. Required fields are marked *