1

Is it correct to call that function in some exceptions ? Is that process correct ? Is it better to process each exceptions ?

def close_all():
        try:
                ftp.close()
        except:
                pass
        try:
                tar.close()
        except:
                pass
        try:
                savelist.close()
        except:
                pass
        try:
                os.remove(tarname)
        except:
                pass
        exit()

Thanks in advance.

vaultah
  • 44,105
  • 12
  • 114
  • 143
Raph
  • 41
  • 4
  • Why not a single `try` if you are going to `pass` all exceptions? – P.P Nov 24 '14 at 15:13
  • 1
    @BlueMoon Because if one throws, the following code won't be executed. I'd recommend not capturing all exceptions though. – Colonel Thirty Two Nov 24 '14 at 15:14
  • Naked `except` is [frowned upon](http://blog.codekills.net/2011/09/29/the-evils-of--except--/) (at the *very least*, use `except Exception`). If you're using Python 3.4, you can use [`contextlib.suppress`](https://docs.python.org/3.4/library/contextlib.html#contextlib.suppress) to make it neater. – jonrsharpe Nov 24 '14 at 15:23
  • See [Why is "except: pass" a bad programming practice?](http://stackoverflow.com/q/21553327) – Martijn Pieters Nov 24 '14 at 15:32

1 Answers1

1

I think you should handle each exception one by one. This will shorten your code. First of all note all the exceptions that ftp.close() and other methods will raise. Then handle them one by one.

Example:

>>> a = 5        # a is an integer
>>> b = "Bingo"  # b is a string
>>>
>>> def add_five():
        try:
            c + 5  # c is not defined. NameError exception is raised
        except NameError:
            b + 5  # b is a string. TypeError exception is raised
        except TypeError:
            a + 5  # a is int. No exception is raised
        except:
            # This last except clause is just in case you forgot to handle any exception
            pass 
>>>
xyres
  • 20,487
  • 3
  • 56
  • 85