[Tutor] file opening and errors.

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Thu Oct 20 20:36:33 CEST 2005



> 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".
>
> With python I have use a try except block but I have no idea how I would
> get the same warning from python as I would from perl (the reason for
> the exception), I am not even sure if this is possible (I assume it must
> be) as google searching has been fruitless.

Hi Dan,

If we leave off an explicit exception handler, any exceptions that happen
will be considered fatal, and will croak out a stack trace, similar to
what Perl does with its Carp module.

For example:

######
>>> open('/foobar')
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
IOError: [Errno 2] No such file or directory: '/foobar'
######

In my own programs, I usually don't do exception handling much because I
do want my programs to fail fast and with a visible stack trace --- the
default error message is usually informative enough.  (I'm usually the
only audience for my programs, so having verbose error messages is
acceptable to me.  *grin*)


Best of wishes to you!



More information about the Tutor mailing list