基本异常处理

bbe*_*ase 0 python exception

我正在尝试执行这个简单的exceptiion处理程序,但由于某种原因它不起作用.我希望它抛出异常并将错误写入文件.

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
Run Code Online (Sandbox Code Playgroud)

我有什么想法我做错了吗?

kqr*_*kqr 5

您的代码段不应引发任何异常.也许你想做点什么

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

另一种可能性是你想说:

try:
    assert g > h
    print 'Hey!'
except AssertionError as e:
    # ...
Run Code Online (Sandbox Code Playgroud)

assert关键字基本上表现得像"故障安全".如果条件为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)
Run Code Online (Sandbox Code Playgroud)

如果你运行它,你会发现你的程序崩溃了.我的Python告诉我:

ZeroDivisionError: integer division or modulo by zero
Run Code Online (Sandbox Code Playgroud)

这是一个例外!发生了异常!当然,你不能除以零.如您所知,此异常是一种信号,可以找到最近的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
Run Code Online (Sandbox Code Playgroud)

现在我们抓住了异常,即异常发生的信号.我们将信号放在变量中e并打印出来.现在你的程序将导致

Something exceptional occurred!
integer division or modulo by zero
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

raise关键字手动发送异常信号.有不同类型的例外,ZeroDivisionError例外,AssertionError例外,NotImplementedError例外和更多例外,但我将这些例外留待进一步研究.

在您的原始代码中,没有任何例外情况发生,所以这就是为什么您从未看到异常被触发的原因.如果你想根据条件(比如g > h)触发异常,你可以使用assert关键字,它的行为有点像raise,但它只在条件为假时引发异常.所以,如果你写

try:
    print 'Is all going well?'
    assert 3 > 5
    print 'Apparently so!'
except AssertionError as e:
    print 'Nope, it does not!'
Run Code Online (Sandbox Code Playgroud)

你永远不会看到"显然是这样!" 消息,因为断言是错误的,它会触发异常.断言对于确保值在程序中有意义并且您希望在不执行时中止当前操作非常有用.

(请注意,我AssertionError在我的异常处理代码中明确地捕获了.这不会捕获其他异常,只有AssertionErrors.如果你继续阅读有关异常的话,你会很快得到它.现在不要过多担心它们.)