我一直在做一些python-couchdb和desktopcouch的工作。在我提交的一个补丁中,我包装了couchdb中的db.update函数。对于任何不熟悉python-couchdb的人来说,该函数如下所示:
def update(self, documents, **options):
"""Perform a bulk update or insertion of the given documents using a
single HTTP request.
>>> server = Server('ht
在python 3中,我如何忽略要向调用方引发的某个异常?
示例:
def do_something():
try:
statement1
statement2
except Exception as e:
# ignore the exception
logging.warning("this is normal, exception is ignored")
try:
do_something()
except Exception as e:
# this is unexpe
假设我有一个代码片段,如下所示
r = requests.post(url, data=values, files=files)
因为这是在发出网络请求,所以可以从这一行抛出一堆异常。为了完整的论证,我也可以让文件读取,发送电子邮件等,以遇到这样的错误,我这样做。
try:
r = requests.post(url, data=values, files=files)
if r.status_code != 200:
raise Exception("Could not post to "+ url)
except Exception as e:
logg
在我设法在高级水平上学习Java之后,我才刚开始学习Python。在带有异常处理的Java输入验证中,异常处理从来都不是一个问题,但在python中,我有点困惑:
这里有一个简单的FizzBuzz程序的例子,它只能读取0到99之间的数字,否则,必须抛出一个异常:
if __name__ == '__main__':
def fizzbuzz(n):
try:
if(0<= n <= 99):
for i in range(n):
if i==0:
我试图理解何时用Python捕获MemoryError是有意义的,我有两个场景:
场景1:成功捕获MemoryError。
import numpy as np
try:
a = np.ones(100000000000)
except MemoryError:
print 'got memory error, plan B'
a = np.ones(10) # this gets created
场景2:我的程序冻结了
silly = []
c = 0
try:
while True:
silly.append((str(c)
在Python中,捕获“所有”异常的最佳方法是什么?
except: # do stuff with sys.exc_info()[1]
except BaseException as exc:
except Exception as exc:
捕获可以在线程中执行。
我的目标是记录普通代码可能抛出的任何异常,而不屏蔽任何特殊的Python异常,例如那些指示进程终止等的异常。
还需要获得异常的句柄(例如通过上面包含exc的子句)。
在Python3中,有一个来重新引发异常。也就是说,如何从引发的异常中找到原始的(/重新引发的)异常?这里有一个(愚蠢的)例子,上面有一些评论来说明我的意思--
def some_func():
try:
None() # TypeError: 'NoneType' object is not callable
except as err:
raise Exception("blah") from err
try:
some_func()
except as err:
# how can I access
我在我的大学上了一个python的初学者课程,明天我还在准备一个关于异常的测试。我正在试着从一个列表中算出几何平均值。当我在列表中输入一个负值时,python会计算几何平均值并给出一个复数(很明显)。然而,在为我的测试做准备时,我希望当列表中有负值时引发异常,但我不知道如何做?有人能帮上忙吗。
我在python3.4中工作。如果你想在这里看到我的代码。关于如何使我的代码更高效的任何其他建议,请让我知道。提前谢谢。
#LOAD A LIST
while True:
try:
我正在我的python代码中自定义异常。我将异常类继承到其他类,现在将一些自定义错误定义为派生自定义异常类的类,如下所示:
class DataCollectorError(Exception): pass
class ParamNullError(DataCollectorError) : pass
class ParamInvalidTypeError(DataCollectorError) : pass
我在python函数中引发这些异常,如下所示:
def READ_METER_DATA (regIndex, numRegisters, slaveUnit):
if not r
在Python中,除了当前函数/方法体中引发的异常之外,我们是否应该在文档字符串中记录可以在其他函数/类中引发的异常?
Obs:我正在考虑使用Google Python docstring风格的
自从我不使用Java已经有很长一段时间了,但是在这里,您会显式地说明您的方法可能会使用"throws“关键字引发什么样的异常。
例如:
class MyException(Exception):
pass
class A(object):
def foo(self):
"""This class does foo
Retu
试图在Python中打开文件的行为会引发异常。如果我使用with语句打开文件,是否可以捕获open调用和相关的__enter__调用引发的异常,而不捕获with块中的代码引发的异常?
try:
with open("some_file.txt") as infile:
print("Pretend I have a bunch of lines here and don't want the `except` below to apply to them")
# ...a bunch more lines of c