8. Exceptions
8. Exceptions
•
•
•
•
•
•
•
•
•
•
•
•
a= 5
b = 0
c = a/b
print(c)
Exception handling is a mechanism to handle errors and other
exceptional events that occur during program execution. When
Python encounters an error, it raises an exception. Exceptions
stop the normal flow of a program, and without handling them,
the program would crash. Using exception handling, you can
define what the program should do when it encounters a
particular error, allowing it to continue running smoothly or to
exit gracefully.
•
•
•
•
Scenario: Ordering Food at a Restaurant
• try: You decide to order a particular dish from the menu and give your order to the
waiter. This is your “try” – the part where you assume things will go smoothly, and
the dish will arrive as expected.
• except:
• Item Out of Stock: If the dish you ordered isn’t available, the waiter (like the
program) will tell you, “Sorry, we’re out of that dish.” You handle this exception by
ordering something else.
• Allergies: Suppose you’re allergic to peanuts, and after ordering, the waiter realizes
the dish contains peanuts. They might warn you to prevent a reaction. In this case,
you would handle this by choosing a different dish or asking for modifications.
else: If there are no issues, the dish you ordered arrives just as you wanted, and you
enjoy your meal. This is like the else block, where everything proceeds as expected
without any issues.
finally: No matter what, you pay the bill at the end. Whether you got the dish you
wanted, had to change your order, or even if there was a delay in service, you still
settle the bill before leaving. The finally block in code works similarly by running at
the end regardless of the outcome, often to clean up resources.
Try-Except Structure:
try:
res = a / b
print('result = ', res)
except:
print('Exception Handled ')
print('End of program’)
import sys
try :
num = int (input('Enter the numerator ') )
den = int (input('Enter the denominator ' ) )
result = num / den;
print('Result = ',result)
except ValueError:
print('Invalid Input')
except ZeroDivisionError:
print('Divide by Zero Error')
print('End of Program ')
#Program to demonstrate multiple except (catch) blocks
try:
a = input('Enter the first number ')
b = input('Enter the second number ')
a = int(a)
res = a + b
print('result = ', res)
except ValueError:
print('Invalid Input Error')
except TypeError:
print('Type Error')
except ZeroDivisionError:
print('Divide by Zero Error')
print('End of program')
• Multiple exceptions can also be put into a single **except** block using
parentheses, to have the **except** block handle all of them.
#Program to demonstrate handling multiple exception types in a single block
import sys
try:
a = input('Enter the first number ')
b = input('Enter the second number ')
a = int(a)
b = int(b)
sum = a + b
print('sum = ', sum)
quotient = a // b
print('quotient = ', quotient)
except (ValueError, TypeError):
print('Invalid Input Error: ', sys.exc_info()[0])
except ZeroDivisionError:
print('Divide by Zero Error')
print('End of program')
try:
print('Enter the marks')
marks = int(input())
if marks < 0 or marks > 100:
raise ValueError
#write code to calculate grade
except ValueError:
print('Input out of range')
def divide (num, den):
try:
res = num / den
return res
except ZeroDivisionError:
print('Divide Function: Divide by Zero Error')
raise
try :
num = int (input('Enter the numerator ') )
den = int (input('Enter the denominator ') )
result = divide (num, den)
print('Result = ', result)
except ValueError:
print('Main Block : Invalid Input ')
except ZeroDivisionError:
print('Main Block: Divide by Zero error')
print('End of Program ')
• To ensure some code runs no matter what errors occur, you can use
a finally statement.
• The finally statement is placed at the bottom of a try/except
statement.
• Code within a finally statement always runs after execution of the
code in the try, and possibly in the except, blocks.
#Program to demonstrate finally blocks
try:
a = int(input('Enter the first number '))
b = int(input('Enter the second number '))
res = a / b
print('result = ', res)
except (ValueError, TypeError):
print('Invalid Input Error')
except ZeroDivisionError:
print('Divide by Zero Error')
finally:
print('This code will run no matter what')
print('End of program')
• Raising exception is similar to throwing exception in
C++/Java.