簡體   English   中英

Python嘗試/除了不工作

[英]Python try/except not working

試圖讓try/except語句工作但遇到問題。 此代碼將獲取一個 txt 文件並將位置第 0 行中的文件復制到第 1 行的位置。但是如果我將其中一個路徑更改為無效的路徑,它會生成錯誤ftplib.error_perm但是除了命令沒有選擇起來,一切都停止了。 我究竟做錯了什么? 蟒蛇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)

except子句只會捕獲在其相應的try塊內raise異常。 嘗試將docopy函數調用也放在try塊中:

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

代碼中引發錯誤的點必須在try塊內。 在這種情況下,錯誤很可能是在docopy函數內部docopy ,但並未包含在try塊中。

請注意, docopy返回None 因此,當您嘗試從None創建iter時,您將引發異常 - 但它不會是ftplib.error_perm異常,它將是TypeError

我知道 OP 是古老的,但對於那些急需回答這個問題的人來說。 我有一個類似的問題,具體取決於您的 IDE,如果您在任何具有特定異常等的行上有斷點,這可能會發生沖突並停止 try/except 執行。

我注意到全局異常可能不起作用,例如,當epub.py模塊執行urllib3連接時Ctrl+C觸發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() 

這個例子對於 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

用法:

@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')

如果您不確定會發生什么異常,請使用下面的代碼,因為如果指定例如:except StandardError: 並且不是那個錯誤,則不會處理異常。

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

好吧,我在 Visual Studio Code 中遇到了同樣的問題,如下所示:

import numpy as np

def func():

    try:

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

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

func()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM