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 and except in Python
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.
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
Introduction to Computing Using Python
VKS-LEARNING HUB
Syntax errors
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.
>>> (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
Introduction to Computing Using Python
VKS-LEARNING HUB
Erroneous state errors
The program execution gets into an erroneous state
>>> 3/0 >>> lst
Traceback (most recent call last): Traceback (most recent call last):
File "<pyshell#56>", line 1, in File "<pyshell#57>", line 1, in
<module> <module>
3/0 lst
ZeroDivisionError: division by NameError: name 'lst' is not defined
zero
>>> lst * lst
>>> lst = [12, 13, 14] Traceback (most recent call last):
>>> lst[3] File "<pyshell#60>", line 1, in
Traceback (most recent call last): <module>
File "<pyshell#59>", line 1, in lst * lst
<module> TypeError: can't multiply sequence by
lst[3] non-int of type 'list’
IndexError: list index out of
range
>>> 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.
Introduction to Computing Using Python
VKS-LEARNING HUB
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
Introduction to Computing Using Python
VKS-LEARNING HUB
Exceptional control flow
Normal control
Exceptional flowflow
control
1. def h(n):
2. print('Start h')
The default behavior is to interrupt the execution of each 3. print(1/n)
“active” statement and print the error information 4. print(n)
5.
contained in the exception object. 6. def g(n):
>>> f(2) 7. print('Start g')
Start f 8. h(n-1)
Start g 9. print(n )
Start h 10.
n = call
Traceback (most recent 2 last): 11. def f(n):
print('Start
File "<pyshell#79>", line 1, in <module> 12. print('Start f')
f(2) f') 13. g(n-1)
g(n-1)
File "/Users/me/ch7/stack.py", n =in1 f
line 13, 14. print(n)
g(n-1) print('Start
File "/Users/me/ch7/stack.py", line 8,g')
in g
h(n-1) h(n-1) n = 0
File "/Users/me/ch7/stack.py", line 3, in h print('Start
print(1/n) h')
ZeroDivisionError: division by zero print(1/n)
>>> print(n) h(0)
print(n) g(1) h(0)
print(n) f(2) g(1)
f(2)
Introduction to Computing Using Python
VKS-LEARNING HUB
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
If an exception is raised while try:
strAge = input('Enter youryour
age:age:
') ')
strAge = input('Enter
executing the try block, then intAge = int(strAge)
intAge = int(strAge)
the block of the associated print('You are {}
print('You areyears old.'.format(intAge))
{} years old.'.format(intAge))
except:
except statement is executed print('Enter your age using digits 0-9!')
Default
Custom behavior:
behavior: The except code block is the exception handler
>>> ========== RESTART ==========
======================== RESTART ========================
>>>
Enter your age: fifteen
Enter your(most
Traceback age using digits
recent call 0-9!
last):
>>>
File "/Users/me/age1.py", line 2, in <module>
intAge = int(strAge)
ValueError: invalid literal for int() with base 10: 'fifteen'
>>>
Introduction to Computing Using Python
VKS-LEARNING HUB
Format of a try/except statement pair
The format of a try/except pair of statements is:
The exception handler handles any
try: exception raised in the try block
<indented code block>
except:
<exception handler block> The except statement is said to
<non-indented statement>
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>
Introduction to Computing Using Python
VKS-LEARNING HUB
Format of a try/except statement pair
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.')
It is possible to restrict the except statement to catch exceptions of
a specific type only
>>> readAge('age.txt')
Value cannot be converted to integer.
1 fifteen >>> readAge('age.text')
Traceback (most recent call last):
age.txt
File "<pyshell#11>", line 1, in <module>
readAge('age.text')
File "/Users/me/ch7.py", line 12, in readAge
default exception infile = open(filename)
handler prints this IOError: [Errno 2] No such file or directory: 'age.text'
>>>
Introduction to Computing Using Python
VKS-LEARNING HUB
Multiple exception handlers
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:
It is#print('Input/Output
executed only if an IOError exception is raised
possible to restrict the except statement to catch exceptions of
error.')
a specific
except type only
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 : How try() works?
try: • First try clause is executed
// Code i.e. the code between try and except clause.
except: • If there is no exception,
// Code then only try clause will run, except clause is
else: (optional) finished.
// code • If any exception occurred, try clause will be
finally : (optional) skipped and except clause will run.
//code • 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