L-5 Exception Handling
L-5 Exception Handling
Exception Handling
in Python
1
Session Overview
Exceptions in Python
Types of Exceptions
Exercise
2
Exceptions in Python
What are Exceptions?
❖An exception is an event, which occurs during the execution of a program and
interrupts its usual flow.
❖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. Since the try block
raises an error, the except block will be executed.
3
Exception Handling Building Blocks
Understanding Exception Handling mechanism
❑The try block lets you test a block of code for errors.
❑You can use the else keyword to define a block of code to be executed if no errors were raised
❑The finally block lets you execute code, regardless of the result of the try- and except blocks.
5
Exceptions in Python (contd.)
Types of Exceptions
❖Example:
try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
else:
print("Nothing went wrong")
finally:
print("The 'try except' is finished")
7
Raise an exception
How to raise an Exception?
❖We can choose to throw an exception if a condition occurs. To throw (or raise) an
exception, use the raise keyword.
❖Example 1:
#Raise an Error if x is negative:
x = -1
if x < 0:
raise Exception("Sorry, no numbers below zero")
❖Example 2:
❖ Python also allows you to create your own exceptions by deriving classes from the standard built-in
exceptions. This is useful when you need to display more specific information when an exception is
caught.
❖ In the try block, the user-defined exception is raised and caught in the except block.
Example:
class OddNumbererror(RuntimeError):
def __init__(self, arg):
self.args = arg
try:
num=int(input("Enter only an even number"))
if(num%2==0):
print(num, " is a Valid even number")
else:
print("Num is odd number")
raise OddNumbererror("Odd Number Error")
except OddNumbererror as e:
9
print ("Odd Number Entered: ",num)
User Defined Exceptions
How to create our own Exceptions?
❖ Python also allows you to create your own exceptions by deriving classes from the standard built-in
exceptions. This is useful when you need to display more specific information when an exception is
caught.
❖ In the try block, the user-defined exception is raised and caught in the except block.
Example:
class OddNumbererror(RuntimeError):
def __init__(self, arg):
self.args = arg
try:
num=int(input("Enter only an even number"))
if(num%2==0):
print(num, " is a Valid even number")
else:
print("Num is odd number")
raise OddNumbererror("Odd Number Error")
except OddNumbererror as e:
10
print ("Odd Number Entered: ",num)
Exercise 17
Time for Action.
11