我正在尝试执行这个简单的异常处理程序,但由于某些原因它无法工作。我希望它抛出异常并将错误写入文件。你知道吗
fileo = "C:/Users/bgbesase/Documents/Brent/ParsePractice/out.txt"
g = 4
h = 6
try:
if g > h:
print 'Hey'
except Exception as e:
f = open(fileo, 'w')
f.truncate()
f.write(e)
f.close()
print e
你知道我做错了什么吗?你知道吗
Tags:
您的代码段不应引发任何异常。也许你想做点像
另一种可能是你想说:
assert
关键字的行为基本上类似于“fail-safe”。如果条件为false,它将引发AssertionError
异常。它通常用于检查函数参数的前提条件。(假设一个值必须大于零,函数才有意义。)编辑:
异常是代码中的一种“信号”,它停止程序正在执行的任何操作,并找到最近的“异常处理程序”。每当程序中发生异常时,所有执行都立即停止,并尝试转到代码中最近的
except:
部分。如果不存在,程序就会崩溃。尝试执行以下程序:如果你运行它,你会看到你的程序崩溃了。我的Python告诉我:
这是个例外!出事了!当然,你不能被零除。如您所知,这个异常是一种信号,它找到最近的
exception:
块,或者异常处理程序。我们可以重写这个程序,这样更安全。你知道吗现在我们捕捉异常,异常发生的信号。我们把信号放在变量
e
中,然后打印出来。现在你的程序将导致当
ZeroDivisionError
异常发生时,它在该点停止执行,并直接转到异常处理程序。如果需要,我们也可以手动引发异常。你知道吗raise
关键字手动发送异常信号。有不同种类的异常,比如ZeroDivisionError
异常,AssertionError
异常,NotImplementedError
异常等等,但我把这些留给进一步的研究。你知道吗在您的原始代码中,没有异常发生,因此您从未看到异常被触发。如果希望基于条件触发异常(如
g > h
),可以使用assert
关键字,其行为有点像raise
,但它仅在条件为false时引发异常。所以如果你写信你永远不会看到“显然如此!”消息,因为断言为false并触发异常。断言有助于确保值在程序中有意义,如果没有意义,则希望中止当前操作
(请注意,我在异常处理代码中显式捕获了
AssertionError
)。这不会捕获其他异常,只捕获AssertionError
s。如果您继续阅读有关异常的内容,您很快就会了解到这一点。现在不要太担心他们。)你从来没有提出过例外。要引发异常,需要将
raise
关键字与Exception
类或Exception
类的实例一起使用。在本例中,我建议使用ValueError
,因为您得到了一个错误的值。你知道吗相关问题 更多 >
编程相关推荐