In this post, we will learn about the try-except block in python with examples and see how and where the try-except block is used.

the try-except block is used to handle errors or exceptions in python. sometimes while running a code it may happen you get an error or exception and the program stop its normal flow of execution, in this case, a try-except block helps you to prevent an error or exception and the program couldn’t stop its execution.

Reasons of Exception

  1. Mismatched Input: Suppose that you are entering your name in place of age, causing an exception because age(data type is Int) and name(data type is a string).
  2. File does not exist: Suppose that you are reading a text file allinpython.txt and that file does not exist in the system, causing exception.
  3. Divide by zero exception: When a number is a divide by zero then the output will be undefined.
  4. IndentationError: If incorrect indentation is given.

try-except block

There are two main keywords are used to solve the problem of exception.

try: In the try block write code which may have exceptions or errors.

except: except block will except error or exception that rises in the try block.

let’s write a program to understand try-except block.

try:
    print(name)
except Exception:
    print("name is not define")

print("allinpython")

Output:

name is not define
allinpython

name is not defined that’s why we get an error but our program does not stop their normal flow of execution (because it also prints allinpython).

write the above program without using try-except block and let’s see what happens.

print(name)

print("name is not define")

print("allinpython")

Output:

allinpython\try-except.py", line 5, in <module>
    print(name)
NameError: name 'name' is not defined
PS C:\Users\saurabh\Desktop\allinpython> python -u "c:\Users\saurabh\Desktop\allinpython\try-except.py"
Traceback (most recent call last):
  File "c:\Users\saurabh\Desktop\allinpython\try-except.py", line 5, in <module>
    print(name)
NameError: name 'name' is not defined

without using the try-except block error rise in the first line and the program stops there execution (couldn’t print allinpython)

Now we understand how and where the try-except block is used.

NOTE

  1. One try block has more than one or multiple except block.
  2. Exception except all kinds of errors (Because Exception is the superclass of all the exceptions).
  3. we can not write except block only (it is compulsory to write try block before except block)
  4. the try-except block is a compulsory block to handle the exception.

try block with multiple except block

def divide(a,b):
    return a/b

try:
    d = divide('4',2)

except ZeroDivisionError as e:
    # print('you can not divide by zero')
    print(e)
except TypeError as e:
    # print('pls enter int value only ')
    print(e)
print("After error")

Output:

unsupported operand type(s) for /: 'str' and 'int'
After error

there are two optional blocks known as the else block and the finally block which is used along with the try-except block.

else: when there is no exception in try block then else block is run.

finally: finally block is always run even if there is an error or not.

NOTE: else and finally block always written after try-except block.

Program with else and finally block

def divide(a,b):
    return a/b

try:
    d = divide(5,0)

except ZeroDivisionError as e:
    # print('you can not divide by zero')
    print(e)
except TypeError as e:
    # print('pls enter int value only ')
    print(e)

else:
    print(d)
finally:
    print("am finally block")

print("Excecution is done")

Output-1:

division by zero
am finally block
Excecution is done

Output-2: if code do not have error (d = divide(10,2))

5.0
am finally block
Excecution is done

Hope this post adds some value to your life -thank you.

Author

Hi, I'm Yagyavendra Tiwari, a computer engineer with a strong passion for programming. I'm excited to share my programming knowledge with everyone here and help educate others in this field.

2 Comments

  1. this website is very helpful for freshers and carriergap students

Reply To Saurabh Cancel Reply