想轻松掌握Python异常捕获 手把手带你完成6题即可
0. 前言由于 Python 直接从源代码运行程序,在 Python 测试或运行代码之前没有编译器进行代码分析,因此测试和异常处理是 Python 程序开发的中的重要组成部分,我们就通过 6 道 Python 编程题来掌握常见异常处理的方法吧!
1. 第 1 题:在单元测试中测试异常
知识点描述:使用测试用例判断异常是否被抛出。
问题描述:测试某个函数抛出的 KeyError 异常的情况,请从以下选项中选出你认为正确的选项:
A.
import unittest
def parse_dict(dictionary, key):
return dictionary
class TestConversion(unittest.TestCase):
def test_bad_key(self):
self.assertRaises(KeyError, parse_dict, 'NULL')
B.
import unittest
def parse_dict(dictionary, key):
return dictionary
class TestConversion(unittest.TestCase):
def test_bad_key(self):
self.assertRaises(KeyError)
C.
import unittest
def parse_dict(key):
return key
class TestConversion(unittest.TestCase):
def test_bad_key(self):
self.assertRaises(KeyError)
D.
import unittest
def parse_dict(key):
return key
class TestConversion(unittest.TestCase):
def test_bad_key(self):
self.assertRaises(KeyError, parse_dict, 'NULL')
正确答案: A2. 第 2 题:多个异常的处理知识点描述:处理一个代码片段可能抛出的多个不同异常。
问题描述:有一个可能抛出多个不同异常的代码段,如何使用简洁的代码处理所有可能的异常:
A.from urllib import error, request
urls = ['https://blog.csdn.net','https://www.baidu.com/aaa', 1, 'https://error.url']
for url in urls:
try:
request.urlopen(url)
except (error.URLError, AttributeError):
urls.remove(url)
print(urls)
B.from urllib import error, request
urls = ['https://blog.csdn.net','https://www.baidu.com/aaa', 1, 'https://error.url']
for url in urls[::-1]:
try:
request.urlopen(url)
except AttributeError:
urls.remove(url)
print(urls)
C.from urllib import error, request
urls = ['https://blog.csdn.net','https://www.baidu.com/aaa', 1, 'https://error.url']
for url in urls[::-1]:
try:
request.urlopen(url)
except error.URLError:
urls.remove(url)
print(urls)
D.from urllib import error, request
urls = ['https://blog.csdn.net','https://www.baidu.com/aaa', 1, 'https://error.url']
for url in urls[::-1]:
try:
request.urlopen(url)
except (error.URLError, AttributeError):
urls.remove(url)
print(urls)
正确答案: D3. 第 3 题:捕获所有异常知识点描述:捕获代码中存在的所有异常。
问题描述:如何捕获代码中存在的所有异常,请从以下选项中选出你认为正确的选项:
A.list_1 = [...]
list_2 = [...]
def add_list(list_1, list_2):
for i in range(len(list_1)):
r = list_1 + list_2
try:
add_list(list_1, list_2)
except Exception as error:
print(e)
B.list_1 = [...]
list_2 = [...]
def add_list(list_1, list_2):
for i in range(len(list_1)):
r = list_1 + list_2
try:
add_list(list_1, list_2)
except Exception as e:
print(e)
C.list_1 = [...]
list_2 = [...]
def add_list(list_1, list_2):
for i in range(len(list_1)):
r = list_1 + list_2
try:
add_list(list_1, list_2)
except Exception:
print(e)
D.list_1 = [...]
list_2 = [...]
def add_list(list_1, list_2):
for i in range(len(list_1)):
r = list_1 + list_2
try:
add_list(list_1, list_2)
except Exception:
print(Exception)
正确答案: B4. 第 4 题:创建自定义异常知识点描述:将异常包装成自定义异常。
问题描述:在构建的网络相关程序中,定义自定义异常,请从以下选项中选出你认为正确的选项:
A.class NetworkError(Exception):
def __init__(self, message, status):
super.__init__(self, message, status)
self.message = message
self.status = status
B.class NetworkError(Exception):
def __init__(self, message, status):
self.message = message
self.status = status
C.class NetworkError(Exception):
def __init__(self, message, status):
super().__init__(self, message, status)
self.message = message
self.status = status
D.class NetworkError(Exception):
def __init__(self, message, status):
super().__init__(message, status)
self.message = message
self.status = status
正确答案: C5. 第 5 题:捕获异常后抛出其他异常知识点描述:捕获一个异常后抛出另一个异常。
问题描述:捕获一个异常后抛出另一个异常,同时在异常回溯中保留两个不同异常的信息,请从以下选项中选出你认为正确的答案:
A.example = {'python': 'simple', 'c': 'fast'}
try:
print(example['java'])
except ValueError as e:
raise RuntimeError('A error occurred') from e
B.example = {'python': 'simple', 'c': 'fast'}
try:
print(example['java'])
except KeyError as e:
raise RuntimeError('A error occurred') from e
C.example = {'python': 'simple', 'c': 'fast'}
try:
print(example['java'])
except TypeError as e:
raise RuntimeError('A error occurred') from e
D.from datetime import datetime
def hello_world(num):
return "Hello world {}!".format(num)
for i in range(10):
with open('log.txt', 'wt') as f:
print(str(datetime.today()) + '\t' + hello_world(i), file=f)
正确答案: B6. 第 6 题:重新抛出被捕获的异常知识点描述:在 except 块中捕获异常后,重新将错误抛出。
问题描述:在一个 except 代码块中捕获一个异常,但是之后想要将其重新抛出,请从以下选项中选出你认为正确的答案:
A.example = {'python': 'simple', 'c': 'fast'}
try:
print(example['java'])
except KeyError as e:
print(example)
raise
B.example = {'python': 'simple', 'c': 'fast'}
try:
print(example['java'])
except KeyError as e:
print(example)
raise RuntimeError
C.example = {'python': 'simple', 'c': 'fast'}
try:
print(example['java'])
except ValueError as e:
print(example)
raise RuntimeError
D.example = {'python': 'simple', 'c': 'fast'}
try:
print(example['java'])
except ValueError as e:
print(example)
raise
正确答案: A试题代码地址https://codechina.csdn.net/LOVEmy134611/python_problem
页:
[1]