Home > Backend Development > Python Tutorial > Summary of python exceptions

Summary of python exceptions

高洛峰
Release: 2016-10-20 09:30:26
Original
1425 people have browsed it

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 "", line 1, in

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(&#39;hyperdrive overload&#39;)   # 添加了一些异常错误信息
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
raise Exception(&#39;hyperdrive overload&#39;)
Exception: hyperdrive overload
Copy after login

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(&#39;Enter the first number: &#39;)
y = input(&#39;Enter the second number: &#39;)
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(&#39;Enter the first number: &#39;)
y = input(&#39;Enter the second number: &#39;)
print x/y
except ZeroDivisionError:
  print "输入的数字不能为0!"
  
#再来运行
>>>
Enter the first number: 10
Enter the second number: 0
Copy after login

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 &#39;Divsion by zero is illagal&#39;
else:
raise
#运行程序:
>>> calculator = MuffledCalulator()
>>> calculator.calc(&#39;10/2&#39;)
5
>>> calculator.clac(&#39;10/0&#39;)
Traceback (most recent call last):
File "<pyshell#30>", line 1, in <module>
calculator.clac(&#39;10/0&#39;)
AttributeError: MuffledCalulator instance has no attribute &#39;clac&#39;   #异常信息被输出了
>>> calculator.muffled = True   #现在打开屏蔽
>>> calculator.calc(&#39;10/0&#39;)
Divsion by zero is illagal
Copy after login


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(&#39;Enter the first number: &#39;)
y = input(&#39;Enter the second number: &#39;)
print x/y
except ZeroDivisionError:
  print "输入的数字不能为0!"
  
#运行输入:
>>>
Enter the first number: 10
Enter the second number: &#39;hello.word&#39;  #输入非数字
Traceback (most recent call last):
File "I:\Python27\yichang", line 4, in <module>
print x/y
TypeError: unsupported operand type(s) for /: &#39;int&#39; and &#39;str&#39;  #又报出了别的异常信息
Copy after login

Okay! We can add an exception handler to handle this situation:

try:
x = input(&#39;Enter the first number: &#39;)
y = input(&#39;Enter the second number: &#39;)
print x/y
except ZeroDivisionError:
print "输入的数字不能为0!"
except TypeError:           # 对字符的异常处理
  print "请输入数字!"
  
#再来运行:
>>>
Enter the first number: 10
Enter the second number: &#39;hello,word&#39;
Copy after login

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(&#39;Enter the first number: &#39;)
y = input(&#39;Enter the second number: &#39;)
print x/y
except (ZeroDivisionError,TypeError,NameError):
print "你的数字不对!
Copy after login

"

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(&#39;Enter the second number: &#39;)
File "<string>", line 0
^
SyntaxError: unexpected EOF while parsing
Copy after login

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(&#39;Enter the first number: &#39;)
y = input(&#39;Enter the second number: &#39;)
print x/y
except:
print &#39;有错误发生了!&#39;
#再来输入一些内容看看
>>>
Enter the first number: &#39;hello&#39; * )0
Copy after login

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(&#39;Enter the first number: &#39;)
y = input(&#39;Enter the second number: &#39;)
value = x/y
print &#39;x/y is&#39;,value
except:
print &#39;列效输入,再来一次!&#39;
#运行
>>>
Enter the first number: 10
Enter the second number:
列效输入,再来一次!
Enter the first number: 10
Enter the second number: &#39;hello&#39;
列效输入,再来一次!
Enter the first number: 10
Enter the second number: 2
x/y is 5
Copy after login



Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template