Python 尝试/除了不工作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14460189/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:33:56  来源:igfitidea点击:

Python try/except not working

pythontry-catchpython-2.4

提问by user1943219

Trying to get the try/exceptstatement working but having problems. This code will take a txt file and copy the file that is in location row 0 to location of row 1. It works however if i change one of the paths to invalid one it generates an error ftplib.error_permhowever the except command is not picking up and everything stops. What am i doing wrong? Python 2.4

试图使try/except语句起作用但遇到问题。此代码将获取一个 txt 文件并将位置第 0 行中的文件复制到第 1 行的位置。但是,如果我将其中一个路径更改为无效路径,它会生成错误,ftplib.error_perm但是没有执行 except 命令和所有内容停止。我究竟做错了什么?蟒蛇 2.4

import csv
import operator
import sys
import os
import shutil
import logging
import ftplib
import tldftp

def docopy(filename):
        ftp = tldftp.dev()
        inf = csv.reader(open(filename,'r'))
        sortedlist = sorted(inf, key=operator.itemgetter(2), reverse=True)
        for row in sortedlist:
                src = row[0]
                dst = row[1]
                tldftp.textXfer(ftp, "RETR " + src, dst)


def hmm(haha):
    result = docopy(haha);
    try:
        it = iter(result)
    except ftplib.error_perm:
        print "Error Getting File" 


if __name__ == "__main__":
        c = sys.argv[1]
        if (c == ''):
                raise Exception, "missing first parameter - row"
        hmm(c)

采纳答案by Xymostech

The exceptclause will only catch exceptions that are raised inside of their corresponding tryblock. Try putting the docopyfunction call inside of the tryblock as well:

except子句将仅捕获raise位于其相应try块内的异常。尝试将docopy函数调用也放在try块内:

def hmm(haha):
    try:
        result = docopy(haha)
        it = iter(result)
    except ftplib.error_perm:
        print "Error Getting File" 

回答by mgilson

The point in the code which raises the error must be inside the tryblock. In this case, it's likely that the error is raised inside the docopyfunction, but that isn't enclosed in a tryblock.

代码中引发错误的点必须在try块内。在这种情况下,错误很可能是在docopy函数内部引发的,但并未包含在try块中。

Note that docopyreturns None. As such, you will raise an exception when you try to make an iterout of None-- but it won't be a ftplib.error_permexception, it'll be a TypeError

请注意,docopy返回None. 因此,当你试图使你将引发异常iter出来的None-但它不会是一个ftplib.error_perm例外,这将是一个TypeError

回答by Matt Heffernan

I know the OP is ancient, but for folks desperate for answers on this question. I had a similar issue, depending on your IDE, if you have a breakpoint on any of the lines with specific exceptions etc, this can conflict and stop try/except executing.

我知道 OP 是古老的,但对于那些急需回答这个问题的人来说。我有一个类似的问题,具体取决于您的 IDE,如果您在任何具有特定异常等的行上有断点,这可能会发生冲突并停止 try/except 执行。

回答by Fruit

I noticed global exception may not works, e.g. , Ctrl+Cwhen epub.pymodule perform urllib3connection trigger KeyboardInterruptbut not able to catch in main thread, the workaround is put my clean up code inside finally, e.g.:

我注意到全局异常可能不起作用,例如,Ctrl+Cepub.py模块执行urllib3连接触发器KeyboardInterrupt但无法在主线程中捕获时,解决方法是将我的清理代码放在里面finally,例如:

try:
    main()
except Exception as e:
    clean_up_stuff()  #this one never called if keyboard interrupt in module urllib3 thread
finally: #but this work
    clean_up_stuff() 

回答by jmunsch

This example is generic for Python3.3+, when decorating a generator function, a decorated generator returns successfully, thus not entering the decorators except, the magic happens with yield from fthus wrapping the yieldable within the decorator:

这个例子对于 Python3.3+ 是通用的,当装饰一个生成器函数时,一个被装饰的生成器成功返回,因此不会进入装饰器,除了,神奇的事情发生在装饰器中yield from f从而将 yieldable 包装在装饰器中:

from types import GeneratorType    

def generic_exception_catcher(some_kwarg: int = 3):
    def catch_errors(func):
        def func_wrapper(*args, **kwargs):
            try:
                f = func(*args, **kwargs)
                if type(f) == GeneratorType:
                    yield from f
                else:
                    return f
            except Exception as e:
                raise e
        return func_wrapper
    return catch_errors

Usage:

用法:

@generic_exception_catcher(some_kwarg=4)
def test_gen():
    for x in range(0, 10):
        raise Exception('uhoh')
        yield x

for y in test_gen():
    print('should catch in the decorator')

回答by LinChina

well, I got the same issue in Visual Studio Code , as:

好吧,我在 Visual Studio Code 中遇到了同样的问题,如下所示:

import numpy as np

def func():

    try:

        a = np.log(-9)
        print(a)

    except:
        print ('exception !') # this will never triggered

func()

回答by renelhs

If you are not sure of what exception will occur, the use the code below, because if especifies for example: except StandardError: and is not that error the exception will not be process.

如果您不确定会发生什么异常,请使用下面的代码,因为如果指定例如:except StandardError: 并且不是那个错误,则不会处理异常。

try:
    # some code
except Exception: # Or only except:
   print "Error" # Python 3: print("Error")