Home > Article > Backend Development > Summary of python exceptions
Python uses exception objects to represent exceptions. When an error is encountered, an exception is thrown. If the exception object is not handled or caught, the program will terminate execution with a so-called traceback (an error message):
>>> 1/0
Traceback (most recent call last):
File "
1/0
ZeroDivisionError: integer division or modulo by zero
raise statement
To raise an exception, you can call raise with a class (a subclass of Exception) or an instance parameter number statement. The following example uses the built-in Exception class:
>>> raise Exception #引发一个没有任何错误信息的普通异常 Traceback (most recent call last): File "<pyshell#1>", line 1, in <module> raise Exception Exception >>> raise Exception('hyperdrive overload') # 添加了一些异常错误信息 Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> raise Exception('hyperdrive overload') Exception: hyperdrive overload
The built-in exception class that comes with the system:
>>> import exceptions
>>> dir(exceptions)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BufferError', 'BytesWarning', 'DeprecationWarning', 'EOFError', 'EnvironmentError', 'Exception', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError ', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TypeError', 'UnboundLocalError ', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '__doc__', '__name__', '__package__']
Wow! There are many commonly used built-in exception classes:
Custom exception
Although the built-in exception classes have covered most situations and are sufficient for many requirements, sometimes you still need to create your own exception class.
Same as other common classes - just make sure to inherit from the Exception class, whether directly or indirectly. Like the following:
>>> class someCustomExcetion(Exception):pass
Of course, you can also add some methods to this class.
Catch exceptions
We can use try/except to implement exception catching and processing.
Suppose you create a program that allows the user to enter two numbers and then divide them:
x = input('Enter the first number: ') y = input('Enter the second number: ') print x/y #运行并且输入 Enter the first number: 10 Enter the second number: 0 Traceback (most recent call last): File "I:/Python27/yichang", line 3, in <module> print x/y ZeroDivisionError: integer division or modulo by zero 为了捕捉异常并做出一些错误处理,可以这样写: try: x = input('Enter the first number: ') y = input('Enter the second number: ') print x/y except ZeroDivisionError: print "输入的数字不能为0!" #再来运行 >>> Enter the first number: 10 Enter the second number: 0
The entered number cannot be 0! #How about it? This time it is much more friendly
It would be better if we raise an exception during debugging. If we do not want the user to see the exception information during the interaction with the user. How to turn on/off the "blocking" mechanism?
class MuffledCalulator: muffled = False #这里默认关闭屏蔽 def calc(self,expr): try: return eval(expr) except ZeroDivisionError: if self.muffled: print 'Divsion by zero is illagal' else: raise #运行程序: >>> calculator = MuffledCalulator() >>> calculator.calc('10/2') 5 >>> calculator.clac('10/0') Traceback (most recent call last): File "<pyshell#30>", line 1, in <module> calculator.clac('10/0') AttributeError: MuffledCalulator instance has no attribute 'clac' #异常信息被输出了 >>> calculator.muffled = True #现在打开屏蔽 >>> calculator.calc('10/0') Divsion by zero is illagal
Multiple except clauses
If you run the above program (enter two numbers and calculate division) and enter the content above, another exception will be generated:
try: x = input('Enter the first number: ') y = input('Enter the second number: ') print x/y except ZeroDivisionError: print "输入的数字不能为0!" #运行输入: >>> Enter the first number: 10 Enter the second number: 'hello.word' #输入非数字 Traceback (most recent call last): File "I:\Python27\yichang", line 4, in <module> print x/y TypeError: unsupported operand type(s) for /: 'int' and 'str' #又报出了别的异常信息
Okay! We can add an exception handler to handle this situation:
try: x = input('Enter the first number: ') y = input('Enter the second number: ') print x/y except ZeroDivisionError: print "输入的数字不能为0!" except TypeError: # 对字符的异常处理 print "请输入数字!" #再来运行: >>> Enter the first number: 10 Enter the second number: 'hello,word'
Please enter a number!
One block to catch multiple exceptions
Of course we can also use one block to catch multiple exceptions:
try: x = input('Enter the first number: ') y = input('Enter the second number: ') print x/y except (ZeroDivisionError,TypeError,NameError): print "你的数字不对!
"
Catch all exceptions
Even if the program handles several exceptions, such as the above After running the program, what if I enter the following content
>>> Enter the first number: 10 Enter the second number: #不输入任何内容,回车 Traceback (most recent call last): File "I:\Python27\yichang", line 3, in <module> y = input('Enter the second number: ') File "<string>", line 0 ^ SyntaxError: unexpected EOF while parsing
faint~! What should I do? There are always situations that we accidentally ignore. If we really want to use a piece of code to catch all exceptions, Then you can ignore all exception classes in the except clause:
try: x = input('Enter the first number: ') y = input('Enter the second number: ') print x/y except: print '有错误发生了!' #再来输入一些内容看看 >>> Enter the first number: 'hello' * )0
An error occurred!
End
Don’t worry! Let’s talk about the last situation, okay, the user accidentally entered the wrong one. Information, can you give me another chance to enter? We can add a loop to ensure that it ends when you lose:
while True: try: x = input('Enter the first number: ') y = input('Enter the second number: ') value = x/y print 'x/y is',value except: print '列效输入,再来一次!' #运行 >>> Enter the first number: 10 Enter the second number: 列效输入,再来一次! Enter the first number: 10 Enter the second number: 'hello' 列效输入,再来一次! Enter the first number: 10 Enter the second number: 2 x/y is 5