LAB 9 : Exception Handling in Python

LAB 9 : Exception Handling in Python

When an error occurs, or exception as we call it, Python will normally stop and generate an error message.

These exceptions can be handled using the try statement

  • The try block lets you test a block of code for errors.
  • The except block lets you handle the error.
  • The finally block lets you execute code, regardless of the result of the try- and except blocks.

Example:This statement will raise an error, because x is not defined

print(x)
Traceback (most recent call last):
  File "<pyshell#26>", line 1, in <module>
    print(x)
NameError: name 'x' is not defined

The try block will generate an exception, because x is not defined.Since the try block raises an error, the except block will be executed.

try:
  print(x)
except:
  print("An exception occurred")
An exception occurred

Many Exceptions

You can define as many exception blocks as you want, e.g. if you want to execute a special block of code for a special kind of error:

Example:Print one message if the try block raises a NameError and another for other errors:

try:
  print(x)
except NameError:
  print("Variable x is not defined")
except:
  print("Something else went wrong")
Variable x is not defined

Else Block

You can use the else keyword to define a block of code to be executed if no errors were raised:

Example:In this example, the try block does not generate any error:

try:
    x=int(input('enter any number:'))
    y=100/x       
except ValueError:
    print('Nothing entered')
except ZeroDivisionError:
    print('enter any number other then Zero')
else:
    print(y)
enter any number:10
10.0

Finally Block

The finally block, if specified, will be executed regardless if the try block raises an error or not.

try:
    x=int(input('enter any number:'))
    y=100/x   
except ValueError:
    print('Nothing entered')
except ZeroDivisionError:
    print('enter any number other then Zero')
else:
    print(y)
finally:
    print('the try : except is finished')
enter any number:0
enter any number other then Zero
the try : except is finished

Raise an exception

As a Python developer you can choose to throw an exception if a condition occurs.To throw (or raise) an exception, use the raise keyword.

Example:Raise an error and stop the program if x is lower than 0

x = -1
if x < 0:
  raise Exception("Sorry, no numbers below zero")
Traceback (most recent call last):
  File "C:/Users/Pallavi/AppData/Local/Programs/Python/Python36/my programs/new module.py", line 3, in <module>
    raise Exception("Sorry, no numbers below zero")
Exception: Sorry, no numbers below zero

The raise keyword is used to raise an exception.

You can define what kind of error to raise, and the text to print to the user.

Example:Raise a TypeError if x is not a string

x = 35
if type(x)!=str:
    raise Exception("Only strings are allowed")
Traceback (most recent call last):
  File "C:/Users/Pallavi/AppData/Local/Programs/Python/Python36/my programs/new module.py", line 3, in <module>
    raise Exception("Only strings are allowed")
Exception: Only strings are allowed