[Tutor] Python equiv of Perl's 'or die()' syntax
Remco Gerlich
scarblac@pino.selwerd.nl
Thu, 20 Jul 2000 00:22:42 +0200
On Wed, Jul 19, 2000 at 05:09:07PM -0500, Ben Beuchler wrote:
> Is there a simple equivalent to Perl's 'or die()' syntax?
>
> Similar to this:
>
> open( MYFILE, 'filethatdoesnotexist') or die "Help me!!:$!"
In Python, error handling is based on the concept of exceptions.
If you try to read a non-existant file with open, open will raise an
exception. If you don't do anything about it, your program will terminate
with "No such file" and a line number. Nothing special to do there.
Dying is hardly ever a useful solution, unless you have a very small script.
(don't know what that means about Perl idioms, don't know enough Perl).
To catch exceptions, you use the try: except: construct, like
try:
f = open("filethatdoesnotexist","r")
except IOError:
print "File open failed!"
# Do the rest of your error handling...
In general, don't look for direct equivalents. Perl is Perl, Python is
Python, they don't do everything in a similar way.
So, I think the answer is "no".
--
Remco Gerlich, scarblac@pino.selwerd.nl