最新消息:XAMPP默认安装之后是很不安全的,我们只需要点击左方菜单的 "安全"选项,按照向导操作即可完成安全设置。

python基础知识-错误提示和异常处理

XAMPP案例 admin 550浏览 0评论

在学习python的时候,你肯定遇到这样提示:

  File "/Users/lifeng/python-projects/Test/pythonScripts/bin/running.py", line 8
    while True print("hello world !")
               ^
SyntaxError: invalid syntax

Process finished with exit code 1

或者这样的提示:

Traceback (most recent call last):
  File "/Users/lifeng/python-projects/Test/pythonScripts/bin/running.py", line 9, in <module>
    print(3 / "3")
TypeError: unsupported operand type(s) for /: 'int' and 'str'

Process finished with exit code 1

以上两种是肯定都会遇到的,第一种是可以避免的,那就是认真学习语法,基础扎实了就不会出现这种语法错误的情况。

第二种是属于python抛出的异常,哪怕语句或表达式使用了正确的语法,执行时仍可能触发错误。执行时检测到的错误称为 异常,异常不一定导致严重的后果,大多数异常不会被程序处理,而是直接抛出异常错误信息

错误信息的最后一行说明程序遇到了什么类型的错误。异常有不同的类型,而类型名称会作为错误信息的一部分中打印出来:上述示例中的异常类型:TypeError。当然这种异常类型只是python提供的一种,还有很多其他类型的异常,可参考官方链接:

官方内置异常访问链接
https://docs.python.org/zh-cn/3/library/exceptions.html#bltin-exceptions

 

异常处理

说到异常处理那就离不开try…expect… ,例如:

try:
    print(a)
except Exception as e:
    print(e)

try块中是正常执行的代码,如果执行正常,那执行结束后会结束程序;如果try块中的代码执行有异常,那就开始执行except块中的代码。

as后面跟随的是一个可自定义的变量,主要是用于接收抛出的异常…

 

try…expect…else语句

try…expect…else 是如果try块执行成功(不报错)就会继续执行else块,如果try块执行有异常就执行expect块,执行完成后就抛出异常,也不在继续执行else块,例如:

try:
    print(2)
except Exception as e:
    print(e)
else:
    print(33)
    
# 运行结果
2
33

Process finished with exit code 0

try…expect…finally语句

try…expect…finally 是如果try块执行成功(不报错)就会继续执行finally块,如果try块执行有异常就执行expect块,执行完成后就抛出异常,继续执行finally块,例如:

try:
    print(a)
except Exception as e:
    raise e
finally:
    print(33)
    
# 运行结果
33
Traceback (most recent call last):
  File "/Users/lifeng/python-projects/Test/pythonScripts/bin/running.py", line 24, in <module>
    raise e
  File "/Users/lifeng/python-projects/Test/pythonScripts/bin/running.py", line 22, in <module>
    print(a)
NameError: name 'a' is not defined

Process finished with exit code 1

如果执行 try 语句时遇到 break 或 return 语句,finally 语句是继续执行的…不受终止影响…

 

触发异常

raise 语句是指强制触发指定异常,例如:

if isinstance(2, str):
    print("2是字符串类型!")
else:
    raise TypeError(f"类型错误:{2}")
    
# 运行结果
Traceback (most recent call last):
  File "/Users/lifeng/python-projects/Test/pythonScripts/bin/running.py", line 12, in <module>
    raise TypeError(f"类型错误:{2}")
TypeError: 类型错误:2

Process finished with exit code 1

而 print 语句是打印输出异常类型的值,例如:

try:
    print(a)
except NameError as e:
    print(e)
    
# 运行结果
name 'a' is not defined

Process finished with exit code 0

 

如果你只是想抛出异常,不打算处理这个异常,就可以使用raise,例如:

try:
    print(a)
except Exception:
    raise
    
# 运行结果
Traceback (most recent call last):
  File "/Users/lifeng/python-projects/Test/pythonScripts/bin/running.py", line 9, in <module>
    print(a)
NameError: name 'a' is not defined

Process finished with exit code 1

Expection是捕获通用异常,是所有内置的非系统退出类异常都派生自此类。所有用户自定义异常也应当派生自此类。

 

异常链

raise 语句支持可选的 from 子句,该子句用于启用链式异常。例如:

raise TypeError("a 未定义!") from e

它的意思就是抛出的第二个异常是第一个异常引起的,例如:

def exc():
    raise NameError


try:
    exc()
except Exception as e:
    raise TypeError("a 未定义!") from e
    
# 运行结果
Traceback (most recent call last):
  File "/Users/lifeng/python-projects/Test/pythonScripts/bin/running.py", line 14, in <module>
    exc()
  File "/Users/lifeng/python-projects/Test/pythonScripts/bin/running.py", line 10, in exc
    raise NameError
NameError

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/Users/lifeng/python-projects/Test/pythonScripts/bin/running.py", line 16, in <module>
    raise TypeError("a 未定义!") from e
TypeError: a 未定义!

Process finished with exit code 1

 

看这句话:The above exception was the direct cause of the following exception

翻译后就是:上述异常是以下异常的直接原因

 

如果想禁用异常链接,from后面变成None即可,例如:

try:
    print(a)
except Exception as e:
    raise TypeError("a 未定义!") from None
    
# 运行结果
Traceback (most recent call last):
  File "/Users/lifeng/python-projects/Test/pythonScripts/bin/running.py", line 16, in <module>
    raise TypeError("a 未定义!") from None
TypeError: a 未定义!

Process finished with exit code 1

dre92

以上总结或许能帮助到你,或许帮助不到你,但还是希望能帮助到你,如有疑问、歧义,直接私信留言会及时修正发布;非常期待你的点赞和分享哟,谢谢!

转载请注明:XAMPP中文组官网 » python基础知识-错误提示和异常处理

您必须 登录 才能发表评论!