Exception Handling
Syntax Error
- Grammatical error
- IDE checks syntax error automatically
- Becasue python’s grammar is simpler relatively, error occur rate is smaller and it is easy to delete errors
Exception
- the cases having no syntax errors, the program can’t progress
- Occuring exception, the program ends
NameError
(Usiung undefined variable)1
4 + boo*3
ZeroDivisionError
(Dividing by0
)1
2
3a = 10
b = 0
c = a / bTypeError
(ex: String + Number type)1
'2' + 2
IndexError
(Using index over the range of index)1
2l = [1,2]
print l[2]KeyError
(Searching dictionary by unregisted key)1
2d = {"a":1, "b":2}
print d['c']IOError
(Opening not existing file)1
a = open('aaa.txt')
How to dispose of exceptions
Using
try
,except
,else
,finally
statements- By expecting the situations making exceptions, we can control the whole code’s flow
try
,except
,else
,finally
- structure
1
2
3
4
5
6
7
8try:
(possible to make errors) usual statements
except Exception:
the statements working when error occurs
else:
the statements working when error doesn't occur
finally:
the statements working anyway no matter error
- structure
Doing exception handling, when error occurs the program doesn’t stop
1
2
3
4
5a = 0
try:
print 1.0/a
except ZeroDivisionError:
print 'zero division error!!!'msg
variable: the message that the person who definedZeroDivisionError
gives
ex: float division by zero1
2
3
4
5
6
7
8def division():
for n in range(0, 5):
try:
print 10.0 / n
except ZeroDivisionError, msg
print msg
division()It can handle the error from the called function in
try
statement indirectly1
2
3
4try:
spam()
except NameError, msg:
print 'Error -', msg,
can be replaced withas
1
2
3
4
5# same code with upper one
try:
spam()
except NameError as msg:
print 'Error -', msgAfter
except
, not evincing any exceptions, it takes care of all exceptions1
2
3
4
5try:
spam()
print 1.0/0.0
except:
print 'Error'About many exceptions, they can be taked care by each
except
statement1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17b = 0.0
name = 'aaa.txt'
try:
print 1.0 / b
spam()
f = open(name, 'r')
'2' + 2
except NameError:
print 'NameError !!!'
except ZeroDivisionError:
print 'ZeroDivisionError !!!'
excpet (TypeError, IOError):
print 'TypeError or IOERror !!!'
else:
print 'No Exception'
finally
print 'Exit !!!'
Catching All exception in same kind
- By using the hierarchy of Inheritance of exception class, It can take care of many exceptions by once
For example, there are
FloatingPointError
,OverflowError
,ZeroDivisionError
as sub-class ofArithmeticError
so, about sub-class exceptions,ArithmeticError
can take care of themWhen an exception is catched by specific
except
, that one is not catched in otherexcept
1
2
3
4
5
6
7
8
9def dosomething():
a = 1/0
try:
dosomething()
except ZeroDivisionError:
print "ZeroDivisionError occured"
except ArithmeticError:
print "ArithmeticError occured"