Mastering Advanced Python Concepts

Try, Except, Else and Finally in Python

Try, Except, Else and Finally in Python

Introduction

In python, an error can be of two types:

  • Syntax errors
  • Exceptions

Syntax errors: Errors are defined as the problems that cause the program to stop its execution.

Exceptions: Exceptions cause a change in the normal flow of the program due to some internal events that occurred in the program.

Some common exceptions are:

IOError: When a file can not be opened this exception is raised.

KeyboardInterrupt: This exception is raised when an unwanted key is pressed.

ValueError: When a wrong argument is passed by the user this exception is raised.

EOFError: When reading a file, if the pointer hit End-Of-File is hit and no data is read from the file.

ImportError: When importing if a module is not found.

Try-Except in Python

In Python, to handle errors in a program, we use a try-except statement.

try block: The try block is used when the code is needed to check for some errors. If there are no errors in the code then the code under the try block will get executed.

except block: Whenever there is some error in the try block preceding the except block, the code under except block executes.

Syntax

try:
    # Some Code to try
except:
    # If an error is present in
    # the code try, then
    # code under except executes.

How does the try-except work

  • First, the try block is executed.
  • If any exception is not there in the code, then the try block will execute, except the block is finished.
  • If an exception occurs then the except block will be executed and the try block is skipped.
  • If an exception is still raised and the except block is left unhandled then it is passed to the outer try blocks. If still it is left unhandled then eventually the execution stops.
  • A try statement can have more than one except block.

Some examples

Code 1

There is no exception, so try block will execute.

def divide(a, b):
try:
res = a // b
print("Answer: ", res)
except ZeroDivisionError:
print("Error dividing it by zero")

divide(3, 2)

Output

Answer: 1

Code 2

An exception is present, so the except block will run.

def divide(a, b):
try:
res = a // b
print("Answer: ", res)
except ZeroDivisionError:
print("Error dividing it by zero")

divide(3, 0)

Output

Error dividing it by zero

write your code here: Coding Playground

Else Block

An else block can also be added on the try-except block and it should be present after all the except blocks. If the try block successfully does not raise an exception then the code enters into the else block.

Syntax

try:
    # Some Code to check for errors
except:
    # if an error in the
    # try block then this block runs
else:
    # executes this block if
    # there is no exception in the try block

Code

def calc(x , y):
try:
z = ((x+y) // (x-y))
except ZeroDivisionError:
print ("The divide is resulting in 0")
else:
print (z)

calc(2.0, 3.0)
calc(3.0, 3.0)

Output

-5.0

The divide is resulting in 0

write your code here: Coding Playground

Finally Keyword

In Python, we use the final keyword, which is executed always even if the exception is not handled and the try-except block is terminated. It is executed after the try-except block.

Syntax

try:
    # Some Code to check for errors
except:
    # If an error in the
    # try block then execute this block
else:
    # If no exception then execute this
finally:
    # This code always executed after the try-except

Code

try:
k = 5//0
print(k)

except ZeroDivisionError:
print("ZeroDivisionError")

finally:
print("The code under finally is always executed")

Output

ZeroDivisionError
The code under finally is always executed

write your code here: Coding Playground