VKS PythonTryException
VKS PythonTryException
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
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
>>> 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
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
try:
<do something>
except Exception:
<handle the error>
The idea of the try-except block is this:
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
VKS-LEARNING HUB
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
try:
<indented code block>
except <ExceptionType>:
<exception handler block>
<non-indented statement>
Introduction to Computing Using Python
VKS-LEARNING HUB
VKS-LEARNING HUB
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
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 = '')
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 = '')
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 ')