Exception Handling in Python using try and except clause – Python 101

If you are a programmer, then you already know, that no one is perfect and you will probably get an error or errors in your Code at some point of time…which can lead to crash your entire program.( Which you usually don’t want this to happen in real-world programs ).

For eg :

def spam(divideBy):
       return 42 / divideBy

print(spam(2))
print(spam(12))
print(spam(0))
print(spam(1))

Output of the above code will be :

 
21.0
3.5
Traceback (most recent call last):
  File "C:/zeroDivide.py", line 6, in 
    print(spam(0))
  File "C:/zeroDivide.py", line 2, in spam
    return 42 / divideBy
ZeroDivisionError: division by zero

This shows …… program crashes when we passed 0 value to the code … we don’t want a situation like this in our Real world’s project …. so, in order to prevent this kind of situation … we use try and except clause
 

for eg :

def spam(divideBy):
    try:
        return 42 / divideBy
    except ZeroDivisionError:
        print('Error: Invalid argument.')

print(spam(2))
print(spam(12))
print(spam(0))
print(spam(1))

When code in a try clause causes an error, the program execution immediately moves to the code in the except clause. After running that code, the execution continues as normal.

Output of the above code :

21.0
3.5
Error: Invalid argument.
None
42.0


Note that any errors that occur in function calls in a try block will also be caught. Consider the following program, which instead has the spam() calls in the try block:

def spam(divideBy):
    return 42 / divideBy

try:
    print(spam(2))
    print(spam(12))
    print(spam(0))
    print(spam(1))
except ZeroDivisionError:
    print('Error: Invalid argument.')

Output :

21.0
3.5
Error: Invalid argument.

The reason print(spam(1)) is never executed is because once the execution jumps to the code in the except clause, it does not return to the try clause. Instead, it just continues moving down as normal.

Exception Handling in Python using try and except clause – Python 101
You may Also Like
Scroll to top