Python异常处理和程序调试

Table of Contents

1. Python中的异常

2. try...except使用

2.1 没有捕获

2.2 添加捕获

3. try...except...finally

4. raise抛出异常

5. 自定义异常

6. assert断言语句使用


1. Python中的异常

2. try...except使用

2.1 没有捕获

#try:
    open("hello.txt")
#except FileNotFoundError:
    print("file not found")
#except:
    print("Program abort")

调试信息(程序异常退出):

C:\Python\Python38\python.exe "E:/python/python project/hello world.py"
  File "E:/python/python project/hello world.py", line 4
    open("hello.txt")
    ^
IndentationError: unexpected indent

Process finished with exit code 1

2.2 添加捕获

try:
    open("hello.txt")
except FileNotFoundError:
    print("file not found")
except:
    print("Program abort")

try:
    result = 10/0
except ZeroDivisionError:
    print("0 is division error")
else:
    print("resule=%d" % result)

调试信息(程序捕获到信息并能够正常运行):

C:\Python\Python38\python.exe "E:/python/python project/hello world.py"
file not found
0 is division error

3. try...except...finally

源码:

try:
    f = open("hello.txt", "r")
except FileNotFoundError:
    print("File not found")
except:
    print("Program abort")
finally:
    print("Exec finally, Close fd")
    f.close()

结果:

C:\Python\Python38\python.exe "E:/python/python project/hello world.py"
Traceback (most recent call last):
file not found
  File "E:/python/python project/hello world.py", line 25, in <module>
0 is division error
    f.close()
NameError: name 'f' is not defined
File not found
Exec finally, Close fd

Process finished with exit code 1

4. raise抛出异常

try:
    s = None
    if s is None:
        print("s is None")
        raise NameError
    print(len(s))

except TypeError:
    print("Null object is no length")
C:\Python\Python38\python.exe "E:/python/python project/hello world.py"
s is None
Traceback (most recent call last):
  File "E:/python/python project/hello world.py", line 7, in <module>
    raise NameError
NameError

Process finished with exit code 1

5. 自定义异常

结果:

6. assert断言语句使用

t = "hello"
assert len(t) > 1

t = "hello"
assert len(t) == 1
C:\Python\Python38\python.exe "E:/python/python project/hello world.py"
Traceback (most recent call last):
  File "E:/python/python project/hello world.py", line 7, in <module>
    assert len(t) == 1
AssertionError

Process finished with exit code 1

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值