What is Exception
In fact Python will report exception when it meet error. if error is not been deal with, the
program will terminate and display a error message(traceback):
>>> 1 / 0
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ZeroDivisionError: integer division or modulo by zero
every exception is a living example of class named ‘ZeroDivisionError’.
In fact we can learn how to make exception first, and then we will learn how to deal with these exception then.
Raise statement
if you want to make exception , you can use raise statement. and make a class(must sub class of Exception) or living example (instantiation) as argument. when you use class as argument, it will create a instantiation . the example next is using inter exception class named “Exception”:
raise Exception
Traceback (most recent call last):
File "<stdin>", line 1, in ?
Exception
>>> raise Exception('hyperdrive overload')
Traceback (most recent call last):
File "<stdin>", line 1, in ?
Exception: hyperdrive overload
In the first example(raise Exception), cause a general exception, which doesn’t point out what exception it caused. In the second example, and a error message “hyperdrive overload”
there are many inter exception class. all these classes can be used in the raise statement:
raise ArithmeticError
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ArithmeticError
name of classes | description |
---|---|
Exception | almost all the exception classes are derived from it |
AttributeError | cause when quote property or when assign value |
OSError | cause when operate system can’t deal with pointed assignment(such as when search file),more than one class |
IndexError | cause when want to use index which not exist. sub class of LookupError |
KeyError | cause when want to use key which not exist. sub class of LookupError |
NameError | cause when can’t find name of variable |
SyntaxError | cause when some code block is wrong |
TypeError | cause when some internal operate or function used for wrong type |
ValueError | cause when some internal operate or function used for object: right type but value wrong |
ZeroDivisionError | cause when second variable is 0 in devision |
Self-defining exception class
If you want to use specific method to deal with specific error, you have to use a self-defining exception class:
how to create a exception class? like create other class, you should inherit directly or indirectly (this means that you can inherit from any internal exception class) so, the code block which creat a self-defining exception class like this :
class SomeCustomException(Exception): pass
it is not difficult (of cause if you want, you can add method in the class).
Catch exception
usually we can deal with the exception and this operation named “catch exception”.
To make this , we can use try/except statement. Assume that you create a program, let user input two number, than make devision. like this :
x = int(input('Enter the first number: '))
y = int(input('Enter the second number: '))
print(x / y)
the program runs well, while the user input 0 as the second number:
Enter the first number: 10
Enter the second number: 0
Traceback (most recent call last):
File "exceptions.py", line 3, in ?
print(x / y)
ZeroDivisionError: integer division or modulo by zero
to catch this exception and deal with the error (print a better message for user), we can rewrite the program like this:
try:
x = int(input('Enter the first number: '))
y = int(input('Enter the second number: '))
print(x / y)
except ZeroDivisionError:
print("The second number can't be zero!")
notice: the exception is broadcast from function to the call function . if not be catch in call function, it will broadcast to top. this means that you can use try/except statement to catch exception created by other people.
Not have to provide arguments
after catching exception, if you want to call it. you can call ‘raise’ statement without argument(of cause you can explicit provide exception catch).
it is very useful, let’s see a calculate class which can restrain exception “ZeroDivisionError”, if we use this usage, the calculator will print a wrong message, not spread the exception. when user use this calculator, it is useful to restrain exception; but when using internal function, spread exception is better way(this time we have not to use the usage), next is a code of class like this :
class MuffledCalculator:
muffled = False
def calc(self, expr):
try:
return eval(expr)
except ZeroDivisionError:
if self.muffled:
print('Division by zero is illegal')
else:
raise
notice: When we divide 0(as second number), if we use ‘restrain’ usage, the method ’ calc ’ will return None. In other word, if we restrain the exception, we should not depend on the return value.
The example below displays usage of this class(includes the on and off restrain usage):