Unit-4: Exceptions
Exception Basics
An exception is an “unwanted or unexpected event”, which
occurs during the execution of the program i.e, at run-time.
This disrupts the normal flow of the program’s instructions.
When an exception occurs, the execution of the program gets
terminated.
Exceptions are special events that can occur due to an error, e.g.
trying to open a file that doesn’t exist
DEPT. OF ISE 2
Exception Basics …
Errors can be handled with try and except statements
The code that could potentially have an error is put in a try
clause.
The program execution moves to the start of a following except
clause if an error happens.
After running that code in except, the execution continues as
normal.
DEPT. OF ISE 3
Exception Basics …
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
print("a/b = %d" %c)
#other code:
print("Hi I am other part of the program")
Enter a:12
Enter b:0
Traceback(most recent call last):
File "exception-test.py", line 3, in <module>
c = a/b;
ZeroDivisionError: division by zero
DEPT. OF ISE 4
Exception Basics …
The try-expect statement
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
except:
print("Can't divide with zero")
Output:
Enter a:30
Enter b:0
Can't divide with zero
DEPT. OF ISE 5
Exception Basics …
Python provides a keyword finally, which is always executed after the
try and except blocks. The final block always executes after the
normal termination of the try block or after the try block terminates
try:
due to some exception
k = 5//0 #k = 5//2
try: print(k)
# Some Code.... except ZeroDivisionError:
print("Can't divide by zero")
except:
finally:
# optional block
print('This is always executed')
# Handling of exception (if required)
else: Can't divide by zero
# execute if no exception This is always executed
finally: 2
This is always executed
# Some code .....(always executed)
DEPT. OF ISE 6
Exception Basics …
We can use the else keyword to define a block of code to be executed if no errors were raised
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
DEPT. OF ISE 7
Exception Basics …
Use of else keyword
def divide(x, y):
try:
result = x // y
except ZeroDivisionError:
print("Sorry ! You are dividing by zero ")
else:
print("Yeah ! Your answer is :", result)
divide(3, 2)
divide(3, 0)
Output:
Yeah ! Your answer is : 1
Sorry ! You are dividing by zero
DEPT. OF ISE 8
Exception Basics …
Python provides a keyword finally, which is always executed after the try and except blocks.
The final block always executes after the normal termination of the try block or after the try block
terminates due to some exception
try:
# Some Code....
except:
# optional block
# Handling of exception (if required)
else:
# execute if no exception
finally:
# Some code .....(always executed)
DEPT. OF ISE 9
Exception Basics …
Use of finally keyword
try:
k = 5//0 #k = 5//2
print(k)
except ZeroDivisionError:
print("Can't divide by zero")
finally:
print('This is always executed')
Can't divide by zero
This is always executed
2
This is always executed
DEPT. OF ISE 10
Exception Basics …
Raise an exception:
There are scenarios where you might want to stop your program by raising an exception if a condition
occurs. You can do this with the raise keyword:
We can throw an exception if a condition occurs. To throw (or raise) an exception, use the raise keyword.
Raise an error and stop the program if x is lower than 0:
x = -1 x = "hello"
if not type(x) is int:
if x < 0: raise TypeError("Only integers are allowed")
raise Exception("Sorry, no numbers below zero")
TypeError: Only integers are allowed
Output:
Exception: Sorry, no numbers below zero
DEPT. OF ISE 11
Exception example
while True:
try:
x = int(input("Please enter a number: "))
break
except ValueError:
print("Oops! That was no valid number. Try again...")
Output:
Please enter a number: 3d
Oops! That was no valid number. Try again...
Please enter a number: 23
DEPT. OF ISE 12
Exception example
def AbyB(a , b):
try:
c = ((a+b) / (a-b))
except ZeroDivisionError:
print ("a/b result in 0")
else:
print (c)
AbyB(2.0, 3.0)
AbyB(3.0, 3.0)
Output:
-5.0
a/b result in 0
DEPT. OF ISE 13
Exception example
class MyException(Exception):
"Invalid marks"
pass
num = 10
Output1:
try: Marks obtained: 10
if num <0 or num>100:
Output2 (num=123):
raise MyException Invalid marks: 123
except MyException as e:
print ("Invalid marks:", num)
else:
print ("Marks obtained:", num)
DEPT. OF ISE 14
Exception example …
Few Examples
Accessing a non−existent dictionary key will raise a KeyError exception.
Searching a list for a non−existent value will raise a ValueError exception.
Calling a non−existent method will raise an AttributeError exception.
Referencing a non−existent variable will raise a NameError exception.
Mixing datatypes without coercion will raise a TypeError exception.
DEPT. OF ISE 15
Exception Basics …
One use of exceptions is to catch a fault and allow the program to continue
working
Exceptions can be created manually in the code by raising an exception.
It operates exactly as a system-caused exceptions, except that the
programmer is doing it on purpose.
Exceptions can be thought of as a special form of the if/elif statements
Proper use of exceptions can help the performance of your program
Exceptions also make code management easier
DEPT. OF ISE 16
Exception Basics …
Advantages of Exception Handling:
Improved program reliability: prevent the program from crashing or producing incorrect results.
Simplified error handling: making it easier to read and maintain your code.
Cleaner code: can avoid using complex conditional statements to check for errors.
Easier debugging: When an exception is raised, the Python interpreter prints a traceback that shows
the exact location where the exception occurred, making it easier to debug your code.
Disadvantages of Exception Handling:
Performance overhead: Exception handling can be slower than using conditional statements to check
for errors.
Increased code complexity: make your code more complex, especially if you have to handle multiple
types of exceptions or implement complex error handling logic.
Possible security risks: Improperly handled exceptions can potentially reveal sensitive information or
create security vulnerabilities in code.
DEPT. OF ISE 17
Exception Class Hierarchy
When an exception occurs, it starts at the lowest level possible (a child) and travels upward
(through the parents), waiting to be caught.
1. If you don’t know what exception may occur, you can always just catch a higher level
exception. if you didn’t know that ZeroDivisionError, you could have used the
ArithmeticError for the exception and caught that (ZeroDivisionError is a child of
ArithmeticError)
2. Multiple exceptions can be treated the same way. suppose you plan on using the
ZeroDivisionError and you want to include the FloatingPointError. If you wanted to have the
same action taken for both errors, simply use the parent exception ArithmeticError as the
exception to catch.
DEPT. OF ISE 18
Exception Class Hierarchy …
DEPT. OF ISE 19
User Defined Exceptions
Python does allow for a programmer to create his own exceptions
To make a custom exception, the programmer determines which base exception to use as the
class to inherit from, e.g. making an exception for negative numbers or one for imaginary
numbers would probably fall under the ArithmeticError exception class. To make a custom
exception, simply inherit the base exception and define what it will do
DEPT. OF ISE 20
User Defined Exceptions …
DEPT. OF ISE 21
User Defined Exceptions …
# define Python user-defined exceptions
class InvalidAgeException(Exception):
"Raised when the input value is less than 18"
pass
# you need to guess this number
number = 18
try:
input_num = int(input("Enter a number: "))
if input_num < number:
raise InvalidAgeException Output1:
Enter a number: 12
else:
Exception occurred: Invalid Age
print("Eligible to Vote") Output2:
Enter a number: 20
except InvalidAgeException: Eligible to Vote
print("Exception occurred: Invalid Age")
DEPT. OF ISE 22
User Defined Exceptions …
# Define a custom exception class
class NotEnoughBalanceError(Exception):
def __init__(self, balance, amount):
self.balance = balance
self.amount = amount
super().__init__(f"Not enough balance ({balance}) to withdraw {amount}")
# Example class representing a bank account
class BankAccount:
def __init__(self, balance):
self.balance = balance
def withdraw(self, amount):
if self.balance < amount:
raise NotEnoughBalanceError(self.balance, amount)
self.balance -= amount
return self.balance
# Example usage
Output:
try:
Not enough balance (100) to withdraw 150
account = BankAccount(100)
withdrawal_amount = 150
remaining_balance = account.withdraw(withdrawal_amount)
print(f"Withdrew {withdrawal_amount}. Remaining balance: {remaining_balance}")
except NotEnoughBalanceError as e:
print(e)
DEPT. OF ISE 23