Dan Klose wrote:
> Hi,
> 
> I usually use perl but fancy a bit of a change so have started playing
> with python.
> 
> using perl to open a file or directory I usually use:
> 
> open(FILE, $file) or die "Error: $!\n";
> 
> The $! is a perl variable that holds an error should the open fail,
> example being : "No such file or directory".

If you want the error to be fatal as in the example above, my recommendation is 
to just use a plain open() call. If the open fails it will raise an exception 
which will be caught by the interpreter. The interpreter will print the text of 
the error and a complete stack trace which can be very useful in locating and 
troubleshooting the error. For example:

 >>> f=open('foo.txt')
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
IOError: [Errno 2] No such file or directory: 'foo.txt'

If you catch the exception and just print the error message you are suppressing 
useful information.

If you want to print the error and continue processing, instead of aborting, 
traceback.print_exc() is handy - it prints the same information as the 
interpreter would. For example:

 >>> import traceback
 >>> def trapper():
 ...   try:
 ...     f = open('foo.txt')
 ...   except IOError:
 ...     traceback.print_exc()
 ...   print 'Still here...'
 ...
 >>> trapper()
Traceback (most recent call last):
  File "<stdin>", line 3, in trapper
IOError: [Errno 2] No such file or directory: 'foo.txt'
Still here...

In these small examples the traceback is not that interesting, but in a larger 
program they can be helpful. Also it is a good habit in general not to suppress 
tracebacks - for file errors you may have a pretty good idea where the problem 
is, but other kinds of errors can be harder to track down.

Kent

_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to