Python try/except not working

user1943219 picture user1943219 · Jan 22, 2013 · Viewed 45.5k times · Source

Trying to get the try/except statement 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_perm however the except command is not picking up and everything stops. What am i doing wrong? Python 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)

Answer

Xymostech picture Xymostech · Jan 22, 2013

The except clause will only catch exceptions that are raised inside of their corresponding try block. Try putting the docopy function call inside of the try block as well:

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