Python 官方文档:入门教程 => 点击学习
目录前言一、异常1.1、忽略1.2、捕获1.3、异常链1.4、自定义1.5、抛出二、异常的显示方式2.1、打印信息2.2、控制台警告2.2、存储文件前言 相比java,python的
相比java,python的异常和java中不同,Python主要是防止程序异常被中止。一旦被catch后它还行往下执行。
pass这个关键字相当于一个占位符,好比TODO是一样的,只表示此行什么也不做,不代表其它的行代码不执行;
def parse_int(s):
try:
n = int(v)
except Exception as e:
print('Could not parse, Reason:', e)
parse_int('30') ##Reason: name 'v' is not defined
try:
client_obj.get_url(url)
except (URLError, ValueError, SocketTimeout):
client_obj.remove_url(url)
try:
client_obj.get_url(url)
except (URLError, ValueError):
client_obj.remove_url(url)
except SocketTimeout:
client_obj.handle_url_timeout(url)
try:
f = open(filename)
except OSError:
pass
class NetworkError(Exception):
pass
class HostnameError(NetworkError):
pass
class CustomError(Exception):
def __init__(self, message, status):
super().__init__(message, status)
self.message = message
self.status = status
try:
msg = s.recv()
except TimeoutError as e:
print(e)
except RuntimeError as e:
print(e.args)
try:
raise RuntimeError('It failed') #抛出新异常-raise Error
except RuntimeError as e:
print(e.args)
def example():
try:
int('N/A')
except ValueError:
print("Didn't work")
raise #捕获后再抛出
try:
print(5/0)
except ZeroDivisionError as e:
print(e.args)
import warnings
warnings.simplefilter('always')
def func(x, y, log_file=None, debug=False):
if log_file is not None:
warnings.warn('log_file argument deprecated', DeprecationWarning)
func(1, 2, 'a')
#第一行日志输出warn内容,第二行输出代码内容
/Users/liudong/personCode/python/pythonTest/app/base/base_type.py:5: UserWarning: log_file argument deprecated
warnings.warn('log_file argument deprecated')
import JSON;
numbers = [2,3,4,5,6];
fileName = "numbers.json";
with open(fileName, "w") as fileObj:
json.dump(numbers, fileObj);
with open(fileName, "r") as fileObj:
number1 = json.load(fileObj);
到此这篇关于Python包装异常处理方法的文章就介绍到这了,更多相关Python 异常处理内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: Python包装异常处理方法
本文链接: https://www.lsjlt.com/news/118887.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0