首页 后端开发 Python教程 python异常大总结

python异常大总结

Oct 20, 2016 am 09:30 AM
python

python用异常对象(exception object)来表示异常情况。遇到错误后,会引发异常。如果异常对象并未被处理或捕捉,程序就会用所谓的 回溯(Traceback, 一种错误信息)终止执行:

>>> 1/0

Traceback (most recent call last):

File "", line 1, in

1/0

ZeroDivisionError: integer division or modulo by zero

raise 语句

为了引发异常,可以使用一个类(Exception的子类)或者实例参数数调用raise 语句。下面的例子使用内建的Exception异常类:

>>> 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
登录后复制

系统自带的内建异常类:

>>> 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__']

哇!好多,常用的内建异常类:

自定义异常

尽管内建的异常类已经包括了大部分的情况,而且对于很多要求都已经足够了,但有些时候还是需要创建自己的异常类。

和常见其它类一样----只是要确保从Exception类继承,不管直接继承还是间接继承。像下面这样:

>>> class someCustomExcetion(Exception):pass

当然,也可以为这个类添加一些方法。

捕捉异常

我们可以使用 try/except 来实现异常的捕捉处理。

假设创建了一个让用户输入两个数,然后进行相除的程序:

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
登录后复制

输入的数字不能为0! #怎么样?这次已经友好的多了

假如,我们在调试的时候引发异常会好些,如果在与用户的进行交互的过程中又是不希望用户看到异常信息的。那如何开启/关闭 “屏蔽”机制?

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
登录后复制


多个except 子句

如果运行上面的(输入两个数,求除法)程序,输入面的内容,就会产生另外一个异常:

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;  #又报出了别的异常信息
登录后复制

好吧!我们可以再加个异常的处理来处理这种情况:

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;
登录后复制

请输入数字!

一个块捕捉多个异常

我们当然也可以用一个块来捕捉多个异常:

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 "你的数字不对!
登录后复制

"

捕捉全部异常

就算程序处理了好几种异常,比如上面的程序,运行之后,假如我输入了下面的内容呢

>>>
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
登录后复制

晕死~! 怎么办呢?总有被我们不小心忽略处理的情况,如果真想用一段代码捕捉所有异常,那么可在except子句中忽略所有的异常类:

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
登录后复制

有错误发生了!

结束

别急!再来说说最后一个情况,好吧,用户不小心输入了错误的信息,能不能再给次机会输入?我们可以加个循环,保你输对时才结束:

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
登录后复制


   


本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

热门话题

Java教程
1662
14
CakePHP 教程
1418
52
Laravel 教程
1311
25
PHP教程
1261
29
C# 教程
1234
24
PHP和Python:解释了不同的范例 PHP和Python:解释了不同的范例 Apr 18, 2025 am 12:26 AM

PHP主要是过程式编程,但也支持面向对象编程(OOP);Python支持多种范式,包括OOP、函数式和过程式编程。PHP适合web开发,Python适用于多种应用,如数据分析和机器学习。

在PHP和Python之间进行选择:指南 在PHP和Python之间进行选择:指南 Apr 18, 2025 am 12:24 AM

PHP适合网页开发和快速原型开发,Python适用于数据科学和机器学习。1.PHP用于动态网页开发,语法简单,适合快速开发。2.Python语法简洁,适用于多领域,库生态系统强大。

PHP和Python:深入了解他们的历史 PHP和Python:深入了解他们的历史 Apr 18, 2025 am 12:25 AM

PHP起源于1994年,由RasmusLerdorf开发,最初用于跟踪网站访问者,逐渐演变为服务器端脚本语言,广泛应用于网页开发。Python由GuidovanRossum于1980年代末开发,1991年首次发布,强调代码可读性和简洁性,适用于科学计算、数据分析等领域。

Python vs. JavaScript:学习曲线和易用性 Python vs. JavaScript:学习曲线和易用性 Apr 16, 2025 am 12:12 AM

Python更适合初学者,学习曲线平缓,语法简洁;JavaScript适合前端开发,学习曲线较陡,语法灵活。1.Python语法直观,适用于数据科学和后端开发。2.JavaScript灵活,广泛用于前端和服务器端编程。

sublime怎么运行代码python sublime怎么运行代码python Apr 16, 2025 am 08:48 AM

在 Sublime Text 中运行 Python 代码,需先安装 Python 插件,再创建 .py 文件并编写代码,最后按 Ctrl B 运行代码,输出会在控制台中显示。

vscode在哪写代码 vscode在哪写代码 Apr 15, 2025 pm 09:54 PM

在 Visual Studio Code(VSCode)中编写代码简单易行,只需安装 VSCode、创建项目、选择语言、创建文件、编写代码、保存并运行即可。VSCode 的优点包括跨平台、免费开源、强大功能、扩展丰富,以及轻量快速。

visual studio code 可以用于 python 吗 visual studio code 可以用于 python 吗 Apr 15, 2025 pm 08:18 PM

VS Code 可用于编写 Python,并提供许多功能,使其成为开发 Python 应用程序的理想工具。它允许用户:安装 Python 扩展,以获得代码补全、语法高亮和调试等功能。使用调试器逐步跟踪代码,查找和修复错误。集成 Git,进行版本控制。使用代码格式化工具,保持代码一致性。使用 Linting 工具,提前发现潜在问题。

notepad 怎么运行python notepad 怎么运行python Apr 16, 2025 pm 07:33 PM

在 Notepad 中运行 Python 代码需要安装 Python 可执行文件和 NppExec 插件。安装 Python 并为其添加 PATH 后,在 NppExec 插件中配置命令为“python”、参数为“{CURRENT_DIRECTORY}{FILE_NAME}”,即可在 Notepad 中通过快捷键“F6”运行 Python 代码。

See all articles