Errors and Exceptions in python

Catching exceptions

Whenever a runtime error occurs, it creates an exception object. The program stops running at this point and Python prints out the traceback, which ends with a message describing the exception that occurred.

Ex→ dividing by zero creates an exception:

>>> print(55 / 0)

Traceback (most recent call last):

 File "<pyshell#0>", line 1, in <module>

 print(55 / 0)

ZeroDivisionError: division by zero

Or trying to make an item assignment on a tuple(Immutable):

>>> tup = ("a", "b", "c", "d")

>>> tup[2] = "c"

Traceback (most recent call last):

 File "<pyshell#3>", line 1, in <module>

 tup[2] = "c"

TypeError: 'tuple' object does not support item assignment

In each case, the error message on the last line has two parts: the type of error before the colon, and specifics about the error after the colon.

Sometimes we want to execute an operation that might cause an exception, but we don’t want the program to stop. We can handle the exception using the try statement to “wrap” a region of code.

Ex→ we might prompt the user for the name of a file and then try to open it. If the file doesn’t exist, we don’t want the program to crash; we want to handle the exception:

filename = input("Enter a file name: ")


    f = open(filename, "r")

except FileNotFoundError:

    print("There is no file named", filename)

Enter a file name: aps

There is no file named aps

The try statement has four separate clauses—or parts—introduced by the keywords try, except, else, and finally.

The interpretor executes the block under the try statement, and monitors for exceptions. If one occurs, the interpretor moves to the except statement; it executes the expect block if the exception raised match the exception requested in the except statement. If no exception occurs, the interpretor skips the block under the except clause. A else block is executed after the try one, if no exception occurred. A finally block is executed in any case.

user_input = input('Type a number:')


   # Try do do something that could fail.

   user_input_as_number = float(user_input)

except ValueError:

   # This will be executed if a ``ValueError`` is raised.

   print('You did not enter a number.')


   # This will be executed if not exception got raised in the

   # ``try`` statement.

   print('The square of your number is ', user_input_as_number**2)


   # This will be executed whether or not an exception is raised.

   print('Thank you')

Type a number:amit

You did not enter a number.

Thank you


Type a number:25

The square of your number is 625.0

Thank you


If the try block can fail in various way, you can handle different exceptions in the same try clause:

It is also possible not to specify a particular exception in the except statement. In this case, any exception will be handled. Such bare except statement should be avoided, though, as they can easily mask bugs.

Raising our own exceptions

If our program detects an error condition, we can raise an exception.

def get_age():

    age = int(input("Please enter your age: "))

    if age < 0:

        # Create a new instance of an exception

        my_error = ValueError("{0} is not a valid age".format(age))

        raise my_error

    return age



Please enter your age: -10

Traceback (most recent call last):

 File "/home/Aps/Documents/card_objects/", line 9, in <module>


 File "/home/Aps/Documents/card_objects/", line 6, in get_age

 raise my_error

ValueError: -10 is not a valid age

exception An error that occurs at runtime.

handle an exception To prevent an exception from causing our program to crash, by wrapping the block of code in a try . . . except construct.

raise To create a deliberate exception by using the raise statement.

reference — Think Python,

Leave a Reply