Exception Handling
Exception Handling
Introduction
A Python program terminates as soon as it
encounters an error.
In Python, an error can be a syntax error or an
exception.
Syntax errors occur when the parser detects an
incorrect statement.
Example of Syntax error
Print( 0 / 0 ))
File "<stdin>", line 1
Print( 0 / 0 ))
^
SyntaxError: invalid syntax
Syntax error is represented with ^ mark. Remove the
extra brace ‘)’
Exception
An exception is an event, which occurs during the
execution of a program that disrupts the normal
flow of the program's instructions.
An exception is a Python object that represents an
error.
When a Python script raises an exception, it must
either handle the exception immediately otherwise
it terminates and quits.
Exception
try:
a = int(input("Enter a positive integer: "))
if a <= 0:
raise ValueError("That is not a positive number!")
except ValueError as ve:
print(ve)
Python try with else clause
Python try with else clause
Python try with else
try:
a = int(input("Enter value of a:"))
b = int(input("Enter value of b:"))
c=a/b
print("a/b = %d" % c)
except ZeroDivisionError:
print("Can't divide by zero")
else:
print("We are in else block ")
Python try with else
try:
# block of code
except Exception1:
# block of code
else:
# this code executes when exceptions not occured
Python try with else and finally clause
try:
a = 10
b=0
c = a/b
print("The answer of a divide by b:", c)
except:
print("Can't divide with zero. Provide different number")
Python try with else and finally clause
try:
a = int(input("Enter value of a:"))
b = int(input("Enter value of b:"))
c = a/b
print("The answer of a divide by b:", c)
except ValueError:
print("Entered value is wrong")
except ZeroDivisionError:
print("Can't divide by zero")
Python try with else and finally clause
Python try with else and finally clause
Python try with else and finally clause
try:
# block of code
# this may throw an exception
finally:
# block of code
# this will always be executed
# after the try and any except block
Python try with else and finally clause
try:
a = int(input("Enter value of a:"))
b = int(input("Enter value of b:"))
c=a/b
print("The answer of a divide by b:", c)
except ZeroDivisionError:
print("Can't divide with zero")
finally:
print("Inside a finally block")
Handling Multiple Exceptions
Often code in try suite can throw more than one type
of exception
Need to write except clause for each type of exception
that needs to be handled
An except clause that does not list a specific
exception will handle any exception that is raised in
the try suite
Should always be last in a series of except clauses
Try
suite
Except(exception1[,exception2[,….exception N]]]):
exception_suite
Else:
else_suite
Try:
a=int(input(“first number”)
b=int(input(“second number”)
result= a/b
print(result)
Except(zerodivisionerror,typeerror):
print(“error occurred”)
Else:
print(“successful Division”)
Displaying an Exception’s
Default Error Message
Exception object: object created in memory when an
exception is thrown
Usually contains default error message pertaining to the
exception
Can assign the exception object to a variable in an
except clause
Example: except ValueError as err:
Can pass exception object variable to print function to
display the default error message
The else Clause
try/except statement may include an optional
else clause, which appears after all the except
clauses
Aligned with try and except clauses
Syntax similar to else clause in decision structure
Else suite: block of statements executed after statements
in try suite, only if no exceptions were raised
If exception was raised, the else suite is skipped
The finally Clause
try/except statement may include an optional
finally clause, which appears after all the except
clauses
Aligned with try and except clauses
General format: finally:
statements
Finally suite: block of statements after the finally clause
Execute whether an exception occurs or not
Purpose is to perform cleanup before exiting
What If an Exception Is Not
Handled?
Two ways for exception to go unhandled:
No except clause specifying exception of the right type
Exception raised outside a try suite
In both cases, exception will cause the program to
halt
Python documentation provides information about
exceptions that can be raised by different functions
Raising an Exceptions
def simple_interest(amount, year, rate):
try:
if rate > 100:
raise ValueError(rate)
interest = (amount * year * rate) / 100
print('The Simple Interest is', interest)
return interest
except ValueError:
print('interest rate is out of range', rate)
print('Case 1')
simple_interest(800, 6, 8)
print('Case 2')
simple_interest(800, 6, 800)
Custom and User-defined Exceptions
class Error(Exception):
"""Base class for other exceptions"""
pass
class ValueTooSmallError(Error):
"""Raised when the input value is small"""
pass
class ValueTooLargeError(Error):
"""Raised when the input value is large"""
pass
Custom and User-defined Exceptions
while(True):
try:
num = int(input("Enter any value in 10 to 50 range: "))
if num < 10:
raise ValueTooSmallError
elif num > 50:
raise ValueTooLargeError
break
except ValueTooSmallError:
print("Value is below range..try again")
except ValueTooLargeError:
print("value out of range...try again")