Dealing with exceptions

Rick Johnson rantingrickjohnson at gmail.com
Sat Mar 2 20:43:05 CET 2013


On Saturday, March 2, 2013 11:40:11 AM UTC-6, bvdp wrote:
> Every time I write a program with exception handling (and
> I suppose that includes just about every program I write!)
> I need to scratch my brain when I create try blocks.
> 
> For example, I'm writing a little program do copy specific
> files to a USB stick. To do the actual copy I'm using:
> 
>     try:
>        shutil.copy(s, os.path.join(usbpath, songname))
>      except ...
> 
> now, I need to figure out just what exceptions to handle.
> Let's see:
> 
> IOError  that means that the disk is full or otherwise
> buggered. Better dump out of the loop.
> 
> But, I know there can be other errors as well. Doing some
> tests, I know that certain filenames are invalid (I think
> a "?" or unicode char is invalid when writing to a FAT32
> filesystem). And, so what exception is that? Without
> actually creating the error, I can't figure it out.

Well how can you expect an error to be thrown without creating the scenario that will throw one? *wink*

> In this case, I can run the program an number of times and
> parse out the errors and write code to catch various
> things. But, I think I'm missing something completely.
> Guess what I'm looking for is a list of possible
> (probable?) errors for the shutil.copy() command. And, in
> a much bigger manual, for most other commands.

No. What you are doing is *misunderstanding* that well written methods must follow the values of:

 "doing one thing and doing it well"
 
In the case of "shutil.copy", that "one thing" is "coping files"; but that "one thing" does NOT include: 

 * resolving file paths
 * validating file path chars on an OS by OS basis
 * ensuring disc space is adequate
 * etc...

Methods that take inputs, like in this case: "src" and "dst" file paths, should not be responsible for the validity of the inputs. It is the responsibility of the caller to validate these inputs PRIOR to injecting them into the method. 

But even *IF* a convincing argument could be made for methods to validate inputs, then at what point do we draw the line? How many foolish samples of the possible permutation set should we consider? Should we inform the user of such foolish usage as:
    
 shutil.copy(src=1, dst=2, follow_symlinks=isinstance)
 shutil.copy(src='cat', dst='hat', follow_symlinks=list)

Now whilst these example are quite absurd, they are in-fact possibilities that must be considered *IF* we intend to follow your "wish" until it's logical conclusion.




More information about the Python-list mailing list