Python 异常


(1)遇见 ZeroDivisionError 异常

print(5/0)

Traceback:

Traceback (most recent call last):
  File "d:/vscode/hello.py", line 1, in <module>
    print(5/0)
ZeroDivisionError: division by zero

(2)使用 try-except 代码块
处理 ZeroDivisionError 异常的 try-except 代码块:

try:
    print(5/0)
except ZeroDivisionError:
    print("You can't divide by zero!")

输出:

You can't divide by zero!

(3)使用 try-except-else 代码块

print("Give me two numbers, and I'll divide them.")
print("Enter 'q' to quit.")
while True:
    first_number = input("\nFirst number: ")
    if first_number == 'q':
        break
    second_number = input("Second number: ")
    try:
        answer = int(first_number) / int(second_number)
    except ZeroDivisionError:
        print("You can't divide by 0!")
    else:
        print(answer)

输出:

First number: 4
Second number: 2
2.0

First number: 4
Second number: 0
You can't divide by 0!

First number: q

(4)处理 FileNotFoundError 异常

filename = 'alice.txt'
with open(filename) as f_obj:
    contents = f_obj.read()

Traceback

Traceback (most recent call last):
  File "d:/vscode/hello.py", line 2, in <module>
    with open(filename) as f_obj:
FileNotFoundError: [Errno 2] No such file or directory: 'alice.txt'

将 try 语句放在包含 open() 的代码行之前:

filename = 'alice.txt'
try:
    with open(filename) as f_obj:
        contents = f_obj.read()
except FileNotFoundError:
    msg = "Sorry, the file " + filename + " does not exist."
    print(msg)

输出:

Sorry, the file alice.txt does not exist.

(5)发生异常时一声不吭(pass)

def count_words(filename):
    """计算一个文件大致包含多少个单词"""
    try:
        with open(filename) as f_obj:
            contents = f_obj.read()
    except FileNotFoundError:
        pass
    else:
        # 计算文件大致包含多少个单词
        words = contents.split()
        num_words = len(words)
        print("The file " + filename + " has about " + str(num_words) + " words.")


filenames = [
    'alice.txt',
    'siddhartha.txt',
    'moby_dick.txt',
]
for filename in filenames:
    count_words(filename)

输出:

PS D:\vscode> & C:/Users/Administrator/AppData/Local/Programs/Python/Python37/python.exe d:/vscode/hello.py
PS D:\vscode>

可以看出,except中使用pass后,什么也不执行了。

(6)存储数据 json.dump()和 json.load()

首先编写存储一组数字的程序,再编写将这些数字读取到内存中的程序。
第一个程序使用json.dump()存储数字

import json
numbers = [2, 3, 5, 7, 11, 13]
filename = 'numbers.json'
with open(filename, 'w') as f_obj:
    json.dump(numbers, f_obj)

输出:numbers.json

[2, 3, 5, 7, 11, 13]

第二个程序使用json.load()读取数字

import json
filename = 'numbers.json'
with open(filename) as f_obj:
    numbers = json.load(f_obj)
print(numbers)

输出:

[2, 3, 5, 7, 11, 13]
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值