Errors and Exceptions

  • Tutorial

Errors and Exceptions in Python

Errors are problems in the program that the program should not recover from. If at any point in the program an error occurs, then the program should exit gracefully. On the other hand, Exceptions are raised when an external event occurs which in some way changes the normal flow of the program.

In this tutorial you will learn about common types of Errors and Exceptions in Python and common paradigms in handling them.

Handling Exceptions with Try/Except/Finally

Errors and Exceptions in Python are handled with the Try: Except: Finally construct. You put the unsafe code in the try: block. You put the fall-back code in the Except: block. The final code is kept in the Finally: block.

For example, look at the code below.

>>> try:
...     print("in the try block")
...     print(1/0)
... except:
...     print("In the except block")
... finally:
...     print("In the finally block")
in the try block
In the except block
In the finally block

Raising exceptions for a predefined condition

Exceptions can also be raised if you want the code to behave within specific parameters. For example, if you want to limit the user-input to only positive integers, raise an exception.

while True:
        user = int(input())
        if user < 0:
        raise ValueError("please give positive number")
        print("user input: %s" % user)
except ValueError as e:

So the output of the above program is:

➜  python
user input: 4
user input: 3
user input: 2
user input: 1
please give positive number
user input: 5
user input: 2
please give positive number
Traceback (most recent call last):
File "", line 3, in <module>
  user = int(input())
Contributed by: Joydeep Bhattacharjee
View All Notifications