Nexusfactor
Nexusfactor

Reputation: 101

Have I Implemented the catch block correcly in Python?

import shutil

def copyDirectory(src, dest):

    try:
        shutil.copytree(src, dest)
    except IOError as why:
        print (why.strerror + ": "  + src)



source="C:/Users/Nexusfactor/Desktop/Copy"
destination="C:/Users/Nexusfactor/Desktop/Destination"

copyDirectory(source, destination)

I've written a script that copies a directory to a destination. Should the source directory not exist then it will print a message saying so.

Question:

Have I done anything in my script that is considered bad practice when trying and catching errors?

Upvotes: 0

Views: 23

Answers (1)

Mahi
Mahi

Reputation: 21942

Your code is basically fine, but are you sure you want to silence the error?

If someone were to use your copyDirectory() function to copy a directory, and then went on to do other stuff, his program will continue to run even though the directory copying failed. It might even raise an other error later on from elsewhere due to this, and it might be harder to trace by then.

Why not just raise an error? Let everyone handle their own failures of copying a directory, as it's usually an essential part of your program that the copying was a success.

Upvotes: 1

Related Questions