KEMBAR78
Python Exception handling using Try-Except-Finally | PPTX
VKS-LEARNING HUB
PYTHON
Types of errors
• There are basically two types of errors:
– syntax errors
– run time errors (program state errors)
>>> excuse = 'I'm sick'
SyntaxError: invalid syntax
>>> print(hour + ':' + minute + ':' + second)
Traceback (most recent call last):
File "<pyshell#113>", line 1, in <module>
print(hour + ':' + minute + ':' + second)
TypeError: unsupported operand type(s) for +: 'int' and 'str’
>>> infile = open('sample.txt')
Traceback (most recent call last):
File "<pyshell#50>", line 1, in <module>
infile = open('sample.txt')
IOError: [Errno 2] No such file or directory: 'sample.txt’
VKS-LEARNING HUB
try() is used in Error and Exception Handling
There are two kinds of errors :
•Syntax Error : Also known as Parsing Errors, most basic. Arise
when the Python parser is unable to understand a line of code.
•Exception : Errors which are detected during execution. eg –
ZeroDivisionError.
try and except in Python
List of Exception Errors :
•IOError : if file can’t be opened
•KeyboardInterrupt : when an unrequired key is pressed by the user
•ValueError : when built-in function receives a wrong argument
•EOFError : if End-Of-File is hit without reading any data
•ImportError : if it is unable to find the module
VKS-LEARNING HUB
Introduction to Computing Using Python
Syntax errors
>>> (3+4]
SyntaxError: invalid syntax
>>> if x == 5
SyntaxError: invalid syntax
>>> print 'hello'
SyntaxError: invalid syntax
>>> lst = [4;5;6]
SyntaxError: invalid syntax
>>> for i in range(10):
print(i)
SyntaxError: expected an indented block
Syntax errors are errors that are due to the incorrect format
of a Python statement
• They occur while the statement is being translated to
machine language and before it is being executed.
VKS-LEARNING HUB
Introduction to Computing Using Python
Erroneous state errors
>>> 3/0
Traceback (most recent call last):
File "<pyshell#56>", line 1, in
<module>
3/0
ZeroDivisionError: division by
zero
The program execution gets into an erroneous state
>>> lst
Traceback (most recent call last):
File "<pyshell#57>", line 1, in
<module>
lst
NameError: name 'lst' is not defined
>>> lst = [12, 13, 14]
>>> lst[3]
Traceback (most recent call last):
File "<pyshell#59>", line 1, in
<module>
lst[3]
IndexError: list index out of
range
>>> lst * lst
Traceback (most recent call last):
File "<pyshell#60>", line 1, in
<module>
lst * lst
TypeError: can't multiply sequence by
non-int of type 'list’
>>> int('4.5')
Traceback (most recent call last):
File "<pyshell#61>", line 1, in <module>
int('4.5')
ValueError: invalid literal for int() with base 10: '4.5'
VKS-LEARNING HUB
when the program execution gets into an erroneous state, an exception
object is created
• This object has a type that is related to the type of error
• The object contains information about the error
• The default behavior is to print this information and interrupt the execution of
the statement that “caused” the error
The reason behind the term “exception” is that when an error occurs and an
exception object is created, the normal execution flow of the program is
interrupted and execution switches to the exceptional control flow
VKS-LEARNING HUB
The idea of the try-except clause is to handle exceptions (errors at runtime).
The syntax of the try-except block is:
try:
<do something>
except Exception:
<handle the error>
The idea of the try-except block is this:
•try: the code with the exception(s) to catch. If an exception is raised, it jumps
straight into the except block.
•except: this code is only executed if an exception occurred in the try block. The
except block is required with a try block, even if it contains only the pass
statement.
It may be combined with the else and finally keywords.
•else: Code in the else block is only executed if no exceptions were raised in the
try block.
•finally: The code in the finally block is always executed, regardless of if a an
exception was raised or not.
VKS-LEARNING HUB
Introduction to Computing Using Python
Exception types
Some of the built-in exception classes:
Exception Explanation
KeyboardInterrupt Raised when user hits Ctrl-C, the interrupt key
OverflowError Raised when a floating-point expression evaluates to a value that is too large
ZeroDivisionError Raised when attempting to divide by 0
IOError Raised when an I/O operation fails for an I/O-related reason
IndexError Raised when a sequence index is outside the range of valid indexes
NameError Raised when attempting to evaluate an unassigned identifier (name)
TypeError Raised when an operation of function is applied to an object of the wrong type
ValueError Raised when operation/function has an argument of the right type but incorrect value
VKS-LEARNING HUB
Introduction to Computing Using Python
Exceptional control flow
>>> f(2)
>>> f(2)
Start f
>>> f(2)
Start f
Start g
>>> f(2)
Start f
Start g
Start h
n = 2
f(2)
n = 1
g(1)
n = 0
h(0)
n = 2
print('Start f')
f(2)
n = 2
print('Start f')
g(n-1)
f(2)
n = 2
print('Start f')
g(n-1)
print(n)
f(2)
n = 1
print('Start g')
g(1)
n = 1
print('Start g')
h(n-1)
g(1)
n = 1
print('Start g')
h(n-1)
print(n)
g(1)
n = 0
print('Start h')
print(1/n)
h(0)
n = 0
print('Start h')
h(0)
n = 0
print('Start h')
print(1/n)
print(n)
h(0)
>>> f(2)
Start f
Start g
Start h
Traceback (most recent call last):
File "<pyshell#79>", line 1, in <module>
f(2)
File "/Users/me/ch7/stack.py", line 13, in f
g(n-1)
File "/Users/me/ch7/stack.py", line 8, in g
h(n-1)
File "/Users/me/ch7/stack.py", line 3, in h
print(1/n)
ZeroDivisionError: division by zero
>>>
Normal control flow
Exceptional control flow
The default behavior is to interrupt the execution of
each “active” statement and print the error information
contained in the exception object.
1. def h(n):
2. print('Start h')
3. print(1/n)
4. print(n)
5.
6. def g(n):
7. print('Start g')
8. h(n-1)
9. print(n )
10.
11. def f(n):
12. print('Start f')
13. g(n-1)
14. print(n)
VKS-LEARNING HUB
Introduction to Computing Using Python
Catching and handling exceptions
It is possible to override the default behavior (print error information
and “crash”) when an exception is raised, using try/except
statements
strAge = input('Enter your age: ')
intAge = int(strAge)
print('You are {} years old.'.format(intAge))
try:
strAge = input('Enter your age: ')
intAge = int(strAge)
print('You are {} years old.'.format(intAge))
except:
print('Enter your age using digits 0-9!')
>>> ======================== RESTART ========================
>>>
Enter your age: fifteen
Traceback (most recent call last):
File "/Users/me/age1.py", line 2, in <module>
intAge = int(strAge)
ValueError: invalid literal for int() with base 10: 'fifteen'
>>>
>>> ========== RESTART ==========
>>>
Enter your age: fifteen
Enter your age using digits 0-9!
>>>
Default behavior:
Custom behavior:
If an exception is raised while
executing the try block, then
the block of the associated
except statement is executed
The except code block is the exception handler
VKS-LEARNING HUB
Introduction to Computing Using Python
Format of a try/except statement pair
try:
<indented code block>
except:
<exception handler block>
<non-indented statement>
The format of a try/except pair of statements is:
The exception handler handles any
exception raised in the try block
The except statement is said to
catch the (raised) exception
It is possible to restrict the except statement to catch exceptions of
a specific type only
try:
<indented code block>
except <ExceptionType>:
<exception handler block>
<non-indented statement>
VKS-LEARNING HUB
>>> readAge('age.txt')
Value cannot be converted to integer.
>>>
Introduction to Computing Using Python
Format of a try/except statement pair
It is possible to restrict the except statement to catch exceptions of
a specific type only
def readAge(filename):
'converts first line of file filename to an integer and prints it'
try:
infile = open(filename)
strAge = infile.readline()
age = int(strAge)
print('age is', age)
except ValueError:
print('Value cannot be converted to integer.')
1 fifteen
age.txt
>>> readAge('age.txt')
Value cannot be converted to integer.
>>> readAge('age.text')
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
readAge('age.text')
File "/Users/me/ch7.py", line 12, in readAge
infile = open(filename)
IOError: [Errno 2] No such file or directory: 'age.text'
>>>
default exception
handler prints this
VKS-LEARNING HUB
Introduction to Computing Using Python
Multiple exception handlers
It is possible to restrict the except statement to catch exceptions of
a specific type only
def readAge(filename):
'converts first line of file filename to an integer and prints it'
try:
infile = open(filename)
strAge = infile.readline()
age = int(strAge)
print('age is',age)
except IOError:
# executed only if an IOError exception is raised
print('Input/Output error.')
except ValueError:
# executed only if a ValueError exception is raised
print('Value cannot be converted to integer.')
except:
# executed if an exception other than IOError or ValueError is raised
print('Other error.')
VKS-LEARNING HUB
Basic Syntax :
try:
// Code
except:
// Code
else: (optional)
// code
finally : (optional)
//code
How try() works?
•First try clause is executed
i.e. the code between try and except clause.
•If there is no exception,
then only try clause will run, except clause is finished.
•If any exception occurred, try clause will be skipped
and except clause will run.
•If any exception occurs,
but the except clause within the code doesn’t handle it,
it is passed on to the outer try statements.
If the exception left unhandled, then the execution
stops.
•A try statement can have more than
one except clause
VKS-LEARNING HUB
# Python code to illustrate
# working of try()
def divide(x, y):
try:
# Floor Division : Gives only
Fractional Part as Answer
result = x // y
print("Yeah ! Your answer is :",
result)
except ZeroDivisionError:
print("Sorry ! You are dividing by
zero ")
# Look at parameters and note the working of Program
divide(3, 2)
Ans. Yeah ! Your answer is : 1
VKS-LEARNING HUB
# Python code to illustrate
# working of try()
def divide(x, y):
try:
# Floor Division : Gives only Fractional Part as Answer
result = x // y
print("Yeah ! Your answer is :", result)
except ZeroDivisionError:
print("Sorry ! You are dividing by zero ")
# Look at parameters and note the working of Program
divide(3, 0)
Ans. Sorry ! You are dividing by zero
VKS-LEARNING HUB
data = 50
try:
data = data/0
except ZeroDivisionError:
print('Cannot divide by 0 ', end = '')
else:
print('Division successful ', end = '')
try:
data = data/5
except:
print('Inside except block ', end = '')
else:
print('VKS', end = '')
a) Cannot divide by 0 VKS
b) Cannot divide by 0
c) Cannot divide by 0 Inside except block VKS
d) Cannot divide by 0 Inside except block
Ans. (a)
Explanation: The else block of code is executed only when there occurs no
exception in try block.
VKS-LEARNING HUB
data = 50
try:
data = data/10
except ZeroDivisionError:
print('Cannot divide by 0 ', end = '')
finally:
print(‘VKS-Learning-Hub ', end = '')
else:
print('Division successful ', end = '')
a) Runtime error
b) Cannot divide by 0 VKS-Learning-Hub
c) VKS-Learning-Hub Division successful
d) VKS-Learning-Hub
Ans. (a)
Explanation: else block following a finally block is not allowed in python. Python
throws syntax error when such format is used.
VKS-LEARNING HUB
value = [1, 2, 3, 4]
data = 0
try:
data = value[4]
except IndexError:
print('VKS', end = '')
except:
print('VKS Learning Hub', end = '')
a) VKS Learning Hub
b) VKS
c) VKS VKS Learning Hub
d) Compilation error
Ans. (b)
Explanation: At a time only one exception is caught, even though the throw exception
in the try block is likely to belong to multiple exception type.
VKS-LEARNING HUB
value = [1, 2, 3, 4]
data = 0
try:
data = value[3]
except IndexError:
print('GFG IndexError ', end = '')
except:
print('VKS Learning Hub IndexError ', end = '')
finally:
print('VKS IndexError ', end = '')
data = 10
try:
data = data/0
except ZeroDivisionError:
print('VKS ZeroDivisionError ', end = '')
finally:
print('VKS ZeroDivisionError ')
a) VKS ZeroDivisionError VKS ZeroDivisionError
b) VKS ZeroDivisionError VKS ZeroDivisionError
c) VKS IndexError VKS ZeroDivisionError VKS ZeroDivisionError
d) VKS IndexError VKS ZeroDivisionError
Ans. (c)
Explanation: finally block of code is always executed whether the exception
occurs or not. If exception occurs, the except block is executed first followed
by finally block.
VKS-LEARNING HUB

Python Exception handling using Try-Except-Finally

  • 1.
  • 2.
    Types of errors •There are basically two types of errors: – syntax errors – run time errors (program state errors) >>> excuse = 'I'm sick' SyntaxError: invalid syntax >>> print(hour + ':' + minute + ':' + second) Traceback (most recent call last): File "<pyshell#113>", line 1, in <module> print(hour + ':' + minute + ':' + second) TypeError: unsupported operand type(s) for +: 'int' and 'str’ >>> infile = open('sample.txt') Traceback (most recent call last): File "<pyshell#50>", line 1, in <module> infile = open('sample.txt') IOError: [Errno 2] No such file or directory: 'sample.txt’
  • 3.
    VKS-LEARNING HUB try() isused in Error and Exception Handling There are two kinds of errors : •Syntax Error : Also known as Parsing Errors, most basic. Arise when the Python parser is unable to understand a line of code. •Exception : Errors which are detected during execution. eg – ZeroDivisionError. try and except in Python List of Exception Errors : •IOError : if file can’t be opened •KeyboardInterrupt : when an unrequired key is pressed by the user •ValueError : when built-in function receives a wrong argument •EOFError : if End-Of-File is hit without reading any data •ImportError : if it is unable to find the module
  • 4.
    VKS-LEARNING HUB Introduction toComputing Using Python Syntax errors >>> (3+4] SyntaxError: invalid syntax >>> if x == 5 SyntaxError: invalid syntax >>> print 'hello' SyntaxError: invalid syntax >>> lst = [4;5;6] SyntaxError: invalid syntax >>> for i in range(10): print(i) SyntaxError: expected an indented block Syntax errors are errors that are due to the incorrect format of a Python statement • They occur while the statement is being translated to machine language and before it is being executed.
  • 5.
    VKS-LEARNING HUB Introduction toComputing Using Python Erroneous state errors >>> 3/0 Traceback (most recent call last): File "<pyshell#56>", line 1, in <module> 3/0 ZeroDivisionError: division by zero The program execution gets into an erroneous state >>> lst Traceback (most recent call last): File "<pyshell#57>", line 1, in <module> lst NameError: name 'lst' is not defined >>> lst = [12, 13, 14] >>> lst[3] Traceback (most recent call last): File "<pyshell#59>", line 1, in <module> lst[3] IndexError: list index out of range >>> lst * lst Traceback (most recent call last): File "<pyshell#60>", line 1, in <module> lst * lst TypeError: can't multiply sequence by non-int of type 'list’ >>> int('4.5') Traceback (most recent call last): File "<pyshell#61>", line 1, in <module> int('4.5') ValueError: invalid literal for int() with base 10: '4.5'
  • 6.
    VKS-LEARNING HUB when theprogram execution gets into an erroneous state, an exception object is created • This object has a type that is related to the type of error • The object contains information about the error • The default behavior is to print this information and interrupt the execution of the statement that “caused” the error The reason behind the term “exception” is that when an error occurs and an exception object is created, the normal execution flow of the program is interrupted and execution switches to the exceptional control flow
  • 7.
    VKS-LEARNING HUB The ideaof the try-except clause is to handle exceptions (errors at runtime). The syntax of the try-except block is: try: <do something> except Exception: <handle the error> The idea of the try-except block is this: •try: the code with the exception(s) to catch. If an exception is raised, it jumps straight into the except block. •except: this code is only executed if an exception occurred in the try block. The except block is required with a try block, even if it contains only the pass statement. It may be combined with the else and finally keywords. •else: Code in the else block is only executed if no exceptions were raised in the try block. •finally: The code in the finally block is always executed, regardless of if a an exception was raised or not.
  • 8.
    VKS-LEARNING HUB Introduction toComputing Using Python Exception types Some of the built-in exception classes: Exception Explanation KeyboardInterrupt Raised when user hits Ctrl-C, the interrupt key OverflowError Raised when a floating-point expression evaluates to a value that is too large ZeroDivisionError Raised when attempting to divide by 0 IOError Raised when an I/O operation fails for an I/O-related reason IndexError Raised when a sequence index is outside the range of valid indexes NameError Raised when attempting to evaluate an unassigned identifier (name) TypeError Raised when an operation of function is applied to an object of the wrong type ValueError Raised when operation/function has an argument of the right type but incorrect value
  • 9.
    VKS-LEARNING HUB Introduction toComputing Using Python Exceptional control flow >>> f(2) >>> f(2) Start f >>> f(2) Start f Start g >>> f(2) Start f Start g Start h n = 2 f(2) n = 1 g(1) n = 0 h(0) n = 2 print('Start f') f(2) n = 2 print('Start f') g(n-1) f(2) n = 2 print('Start f') g(n-1) print(n) f(2) n = 1 print('Start g') g(1) n = 1 print('Start g') h(n-1) g(1) n = 1 print('Start g') h(n-1) print(n) g(1) n = 0 print('Start h') print(1/n) h(0) n = 0 print('Start h') h(0) n = 0 print('Start h') print(1/n) print(n) h(0) >>> f(2) Start f Start g Start h Traceback (most recent call last): File "<pyshell#79>", line 1, in <module> f(2) File "/Users/me/ch7/stack.py", line 13, in f g(n-1) File "/Users/me/ch7/stack.py", line 8, in g h(n-1) File "/Users/me/ch7/stack.py", line 3, in h print(1/n) ZeroDivisionError: division by zero >>> Normal control flow Exceptional control flow The default behavior is to interrupt the execution of each “active” statement and print the error information contained in the exception object. 1. def h(n): 2. print('Start h') 3. print(1/n) 4. print(n) 5. 6. def g(n): 7. print('Start g') 8. h(n-1) 9. print(n ) 10. 11. def f(n): 12. print('Start f') 13. g(n-1) 14. print(n)
  • 10.
    VKS-LEARNING HUB Introduction toComputing Using Python Catching and handling exceptions It is possible to override the default behavior (print error information and “crash”) when an exception is raised, using try/except statements strAge = input('Enter your age: ') intAge = int(strAge) print('You are {} years old.'.format(intAge)) try: strAge = input('Enter your age: ') intAge = int(strAge) print('You are {} years old.'.format(intAge)) except: print('Enter your age using digits 0-9!') >>> ======================== RESTART ======================== >>> Enter your age: fifteen Traceback (most recent call last): File "/Users/me/age1.py", line 2, in <module> intAge = int(strAge) ValueError: invalid literal for int() with base 10: 'fifteen' >>> >>> ========== RESTART ========== >>> Enter your age: fifteen Enter your age using digits 0-9! >>> Default behavior: Custom behavior: If an exception is raised while executing the try block, then the block of the associated except statement is executed The except code block is the exception handler
  • 11.
    VKS-LEARNING HUB Introduction toComputing Using Python Format of a try/except statement pair try: <indented code block> except: <exception handler block> <non-indented statement> The format of a try/except pair of statements is: The exception handler handles any exception raised in the try block The except statement is said to catch the (raised) exception It is possible to restrict the except statement to catch exceptions of a specific type only try: <indented code block> except <ExceptionType>: <exception handler block> <non-indented statement>
  • 12.
    VKS-LEARNING HUB >>> readAge('age.txt') Valuecannot be converted to integer. >>> Introduction to Computing Using Python Format of a try/except statement pair It is possible to restrict the except statement to catch exceptions of a specific type only def readAge(filename): 'converts first line of file filename to an integer and prints it' try: infile = open(filename) strAge = infile.readline() age = int(strAge) print('age is', age) except ValueError: print('Value cannot be converted to integer.') 1 fifteen age.txt >>> readAge('age.txt') Value cannot be converted to integer. >>> readAge('age.text') Traceback (most recent call last): File "<pyshell#11>", line 1, in <module> readAge('age.text') File "/Users/me/ch7.py", line 12, in readAge infile = open(filename) IOError: [Errno 2] No such file or directory: 'age.text' >>> default exception handler prints this
  • 13.
    VKS-LEARNING HUB Introduction toComputing Using Python Multiple exception handlers It is possible to restrict the except statement to catch exceptions of a specific type only def readAge(filename): 'converts first line of file filename to an integer and prints it' try: infile = open(filename) strAge = infile.readline() age = int(strAge) print('age is',age) except IOError: # executed only if an IOError exception is raised print('Input/Output error.') except ValueError: # executed only if a ValueError exception is raised print('Value cannot be converted to integer.') except: # executed if an exception other than IOError or ValueError is raised print('Other error.')
  • 14.
    VKS-LEARNING HUB Basic Syntax: try: // Code except: // Code else: (optional) // code finally : (optional) //code How try() works? •First try clause is executed i.e. the code between try and except clause. •If there is no exception, then only try clause will run, except clause is finished. •If any exception occurred, try clause will be skipped and except clause will run. •If any exception occurs, but the except clause within the code doesn’t handle it, it is passed on to the outer try statements. If the exception left unhandled, then the execution stops. •A try statement can have more than one except clause
  • 15.
    VKS-LEARNING HUB # Pythoncode to illustrate # working of try() def divide(x, y): try: # Floor Division : Gives only Fractional Part as Answer result = x // y print("Yeah ! Your answer is :", result) except ZeroDivisionError: print("Sorry ! You are dividing by zero ") # Look at parameters and note the working of Program divide(3, 2) Ans. Yeah ! Your answer is : 1
  • 16.
    VKS-LEARNING HUB # Pythoncode to illustrate # working of try() def divide(x, y): try: # Floor Division : Gives only Fractional Part as Answer result = x // y print("Yeah ! Your answer is :", result) except ZeroDivisionError: print("Sorry ! You are dividing by zero ") # Look at parameters and note the working of Program divide(3, 0) Ans. Sorry ! You are dividing by zero
  • 17.
    VKS-LEARNING HUB data =50 try: data = data/0 except ZeroDivisionError: print('Cannot divide by 0 ', end = '') else: print('Division successful ', end = '') try: data = data/5 except: print('Inside except block ', end = '') else: print('VKS', end = '') a) Cannot divide by 0 VKS b) Cannot divide by 0 c) Cannot divide by 0 Inside except block VKS d) Cannot divide by 0 Inside except block Ans. (a) Explanation: The else block of code is executed only when there occurs no exception in try block.
  • 18.
    VKS-LEARNING HUB data =50 try: data = data/10 except ZeroDivisionError: print('Cannot divide by 0 ', end = '') finally: print(‘VKS-Learning-Hub ', end = '') else: print('Division successful ', end = '') a) Runtime error b) Cannot divide by 0 VKS-Learning-Hub c) VKS-Learning-Hub Division successful d) VKS-Learning-Hub Ans. (a) Explanation: else block following a finally block is not allowed in python. Python throws syntax error when such format is used.
  • 19.
    VKS-LEARNING HUB value =[1, 2, 3, 4] data = 0 try: data = value[4] except IndexError: print('VKS', end = '') except: print('VKS Learning Hub', end = '') a) VKS Learning Hub b) VKS c) VKS VKS Learning Hub d) Compilation error Ans. (b) Explanation: At a time only one exception is caught, even though the throw exception in the try block is likely to belong to multiple exception type.
  • 20.
    VKS-LEARNING HUB value =[1, 2, 3, 4] data = 0 try: data = value[3] except IndexError: print('GFG IndexError ', end = '') except: print('VKS Learning Hub IndexError ', end = '') finally: print('VKS IndexError ', end = '') data = 10 try: data = data/0 except ZeroDivisionError: print('VKS ZeroDivisionError ', end = '') finally: print('VKS ZeroDivisionError ') a) VKS ZeroDivisionError VKS ZeroDivisionError b) VKS ZeroDivisionError VKS ZeroDivisionError c) VKS IndexError VKS ZeroDivisionError VKS ZeroDivisionError d) VKS IndexError VKS ZeroDivisionError Ans. (c) Explanation: finally block of code is always executed whether the exception occurs or not. If exception occurs, the except block is executed first followed by finally block.
  • 21.