Try, Except, else and Finally in Python

An Exception is an Event, which occurs during the execution of the program. It is also Knows as a run time error. When that error occurs, Python generates an exception during the execution and that can be handled, which avoids your program to interrupt.

Example:

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

a = 5
b = 0
print(a/b)

chevron_right


Output:

Traceback (most recent call last):
  File "/home/8a10be6ca075391a8b174e0987a3e7f5.py", line 3, in <module>
    print(a/b)
ZeroDivisionError: division by zero

In this code, The system can not divide the number with zero then an exception is raised. 

Exception handling with try, except, else and finally

  • Try: This bock will test the excepted error to occur.
  • Except:  Here you can handle the error
  • Else: If there is not any exception then this block will be executed. 
  • Finally: Finally block always executed either exception generating or not

Syntax:



try:
       # Some Code.... 

except:
       # optional block
       # Handling of exception (if required)

else:
       # execute if no exception

finally:
      # Some code .....(always executed)

Let’s first understand how the try and except works –

  • First try clause is executed i.e. the code between try and except clause.
  • If there is no exception, then only try clause will run, except clause is finished.
  • If any exception occurred, the try clause will be skipped and except clause will run.
  • If any exception occurs, but the except clause within the code doesn’t handle it, it is passed on to the outer try statements. If the exception left unhandled, then the execution stops.
  • A try statement can have more than one except clause

Example: Let us try to take user Integer input and throw the exception in except block.

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to illustrate 
# working of try()  
def divide(x, y): 
    try
        # Floor Division : Gives only Fractional
        # Part as Answer 
        result = x //
        print("Yeah ! Your answer is :", result) 
    except ZeroDivisionError: 
        print("Sorry ! You are dividing by zero "
    
# Look at parameters and note the working of Program 
divide(3, 2
divide(3, 0)

chevron_right


Output:

Yeah ! Your answer is : 1
Sorry ! You are dividing by zero 

Else Clause

The code enters the else block only if the try clause does not raise an exception.

Example: Else block will execute when no exception occurs.

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to illustrate 
# working of try()  
def divide(x, y): 
    try
        # Floor Division : Gives only Fractional
        # Part as Answer 
        result = x //
    except ZeroDivisionError: 
        print("Sorry ! You are dividing by zero "
    else:
        print("Yeah ! Your answer is :", result) 
    
# Look at parameters and note the working of Program 
divide(3, 2
divide(3, 0)

chevron_right


Output:

Yeah ! Your answer is : 1
Sorry ! You are dividing by zero

Finally Keyword

Python provides a keyword finally, which is always executed after try and except blocks. The finally block always executes after normal termination of try block or after try block terminates due to some exception.

Example: Let’s try to throw the exception in except block and Finally will execute either exception will generate or not

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to illustrate 
# working of try()  
def divide(x, y): 
    try
        # Floor Division : Gives only Fractional 
        # Part as Answer 
        result = x //
    except ZeroDivisionError: 
        print("Sorry ! You are dividing by zero "
    else:
        print("Yeah ! Your answer is :", result) 
    finally:  
        # this block is always executed   
        # regardless of exception generation.  
        print('This is always executed')   
  
# Look at parameters and note the working of Program 
divide(3, 2
divide(3, 0)

chevron_right


Output:

Yeah ! Your answer is : 1
This is always executed
Sorry ! You are dividing by zero 
This is always executed

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.