Exception raise
Occuring exception by raise
raise
keyword can make an exception in specific situationIndexError
occurs when__getitem__
method(which implements indexing when sequance type class is made) goes out of the index range1
2
3
4
5
6
7
8
9
10
11
12
13
14
15class SquareSeq:
def __init__(self, n):
self.n = n
def __getitem__(self,k):
if k >= self.n or k < 0:
raise IndexError # out of index range, IndexError occurs
return k * k
def __len_(self):
return self.n
s = SquareSeq(10)
print s[2], s[4]
for x in s: # repeating until IndexError occurs
print x,
print s[20] # out of the index range
Customized exception class
- Generally It is implemented by extending
Exception
class
(Other exceptions are unusual) - How to raise the exception
- Same to built-in exception. Using
raise [class instance]
- Same to built-in exception. Using
- How to catch the exception from Customized exception class
- Using the class’ name like
except [class name]
- Using the class’ name like
In the example below,
except Big
catchesBig
andSmall
exception
-> BecauseSmall
isBig
‘s sub-class’1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18class Big(Exception):
pass
class Small(Big):
pass
def dosomething1():
x = Big()
raise x # x is exception object, it can use raise
def dosomething2():
raise Small()
for f in (dosomething1, dosomething2):
try:
f()
except Big:
print "Exception occurs!"
Passing exception
After
raise
keyword, with exception, additional message can follow1
2
3
4
5
6
7def f():
raise Exception, 'message!!!'
try:
f()
except Exception, a:
print aWhen
except
keyword is used, exception message in initializer can be taken as 2nd parameter.1
2
3
4
5
6
7
8a = 10
b = 0
try:
if b == 0:
raise ArithmeticError('you are dividing by 0')
a/b
except ArithmeticError, v:
print v