亲宝软件园·资讯

展开

Python 异常处理

生而为人我很遗憾 人气:0

前言

相比java,python的异常和java中不同,python主要是防止程序异常被中止。一旦被catch后它还行往下执行。

一、异常

1.1、忽略

pass这个关键字相当于一个占位符,好比TODO是一样的,只表示此行什么也不做,不代表其它的行代码不执行;

try:
print(5/0)
except ZeroDivisionError:
pass
print("ddd") #这行还是可以正常执行的

1.2、捕获

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

1.3、异常链

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

1.4、自定义

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)

1.5、抛出

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 #捕获后再抛出

二、异常的显示方式

2.1、打印信息

try:
print(5/0)
except ZeroDivisionError as e:
print(e.args)

2.2、控制台警告

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')

2.2、存储文件

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);

加载全部内容

相关教程
猜你喜欢
用户评论