Exception Handling
Exception Handling
Exceptions: Exceptions are raised when the program is syntactically correct, but the code results
in an error. This error does not stop the execution of the program, however, it changes the
normal flow of the program.
Syntax Error Example
# initialize the amount variable
amount = 10000
# check that You are eligible to
# purchase Dsa Self Paced or not
if(amount > 2999)
print("You are eligible to purchase Dsa Self Paced")
Exception Example
# initialize the amount variable
marks = 10000
try:
# statement(s)
except IndexError:
# statement(s)
except ValueError:
# statement(s)
Example: Catching specific exceptions in the Python
# Program to handle multiple errors with one # except statement
def fun(a):
if a < 4:
# throws ZeroDivisionError for a = 3
b = a/(a-3)
# throws NameError if a >= 4
print("Value of b = ", b)
try:
fun(3)
fun(5)
# note that braces () are necessary here for multiple exceptions
except ZeroDivisionError:
print("ZeroDivisionError Occurred and Handled")
except NameError:
print("NameError Occurred and Handled")
print(“Thanks”)
Try with Else Clause
In Python, you can also use the else clause on the try-except block which must be present after
all the except clauses. The code enters the else block only if the try clause does not raise an
exception.
# Program to depict else clause with try-except
# Function which returns a/b
def AbyB(a , b):
try:
c = ((a+b) / (a-b))
except ZeroDivisionError:
print ("a/b result in 0")
else:
print (c)
# Driver program to test above function
AbyB(2.0, 3.0)
AbyB(3.0, 3.0)
Finally Keyword in Python
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.
Syntax:
try:
# Some Code....
except:
# optional block
# Handling of exception (if required)
else:
# execute if no exception
finally:
# Some code .....(always executed)
Example
# No exception Exception raised in try block
try:
k = 5//0 # raises divide by zero exception.
print(k)
finally:
# this block is always executed
# regardless of exception generation.
print('This is always executed')
Advantages of Exception Handling:
Improved program reliability: By handling exceptions properly, you can prevent your program
from crashing or producing incorrect results due to unexpected errors or input.
Simplified error handling: Exception handling allows you to separate error handling code from
the main program logic, making it easier to read and maintain your code.
Cleaner code: With exception handling, you can avoid using complex conditional statements to
check for errors, leading to cleaner and more readable code.
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.
Thanks