基本异常处理

2024-09-25 20:29:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试执行这个简单的异常处理程序,但由于某些原因它无法工作。我希望它抛出异常并将错误写入文件。你知道吗

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: 文件txt处理程序if错误原因outusers
2条回答

您的代码段不应引发任何异常。也许你想做点像

try:
    if g > h:
        print 'Hey'
    else:
        raise NotImplementedError('This condition is not handled here!')
except Exception as e:
    # ...

另一种可能是你想说:

try:
    assert g > h
    print 'Hey!'
except AssertionError as e:
    # ...

assert关键字的行为基本上类似于“fail-safe”。如果条件为false,它将引发AssertionError异常。它通常用于检查函数参数的前提条件。(假设一个值必须大于零,函数才有意义。)


编辑:

异常是代码中的一种“信号”,它停止程序正在执行的任何操作,并找到最近的“异常处理程序”。每当程序中发生异常时,所有执行都立即停止,并尝试转到代码中最近的except:部分。如果不存在,程序就会崩溃。尝试执行以下程序:

print 'Hello. I will try doing a sum now.'
sum = 3 + 5
print 'This is the sum: ' + str(sum)
print 'Now I will do a division!'
quotient = 5/0
print 'This is the result of that: ' + str(quotient)

如果你运行它,你会看到你的程序崩溃了。我的Python告诉我:

ZeroDivisionError: integer division or modulo by zero

这是个例外!出事了!当然,你不能被零除。如您所知,这个异常是一种信号,它找到最近的exception:块,或者异常处理程序。我们可以重写这个程序,这样更安全。你知道吗

try:
    print 'Hello. I will try doing a sum now.'
    sum = 3 + 5
    print 'This is the sum: ' + str(sum)
    print 'Now I will do a division!'
    quotient = 5/0
    print 'This is the result of that: ' + str(quotient)
except Exception as e:
    print 'Something exceptional occurred!'
    print e

现在我们捕捉异常,异常发生的信号。我们把信号放在变量e中,然后打印出来。现在你的程序将导致

Something exceptional occurred!
integer division or modulo by zero

ZeroDivisionError异常发生时,它在该点停止执行,并直接转到异常处理程序。如果需要,我们也可以手动引发异常。你知道吗

try:
    print 'This you will see'
    raise Exception('i broke your code')
    print 'This you will not'
except Exception as e:
    print 'But this you will. And this is the exception that occurred:'
    print e

raise关键字手动发送异常信号。有不同种类的异常,比如ZeroDivisionError异常,AssertionError异常,NotImplementedError异常等等,但我把这些留给进一步的研究。你知道吗

在您的原始代码中,没有异常发生,因此您从未看到异常被触发。如果希望基于条件触发异常(如g > h),可以使用assert关键字,其行为有点像raise,但它仅在条件为false时引发异常。所以如果你写信

try:
    print 'Is all going well?'
    assert 3 > 5
    print 'Apparently so!'
except AssertionError as e:
    print 'Nope, it does not!'

你永远不会看到“显然如此!”消息,因为断言为false并触发异常。断言有助于确保值在程序中有意义,如果没有意义,则希望中止当前操作

(请注意,我在异常处理代码中显式捕获了AssertionError)。这不会捕获其他异常,只捕获AssertionErrors。如果您继续阅读有关异常的内容,您很快就会了解到这一点。现在不要太担心他们。)

你从来没有提出过例外。要引发异常,需要将raise关键字与Exception类或Exception类的实例一起使用。在本例中,我建议使用ValueError,因为您得到了一个错误的值。你知道吗

fileo = "C:/Users/bgbesase/Documents/Brent/ParsePractice/out.txt"

g = 4
h = 6
try:
    if g > h:
        raise ValueError('Hey')
except Exception as e:
    f = open(fileo, 'w')
    f.truncate()
    f.write(str(e))
    f.close()
    print e

相关问题 更多 >