Loginskip to content

October 30th, 2006

Other operating systems may handle this case differently.

but this is rather ineffectual for several reasons. First, we don’t know why the program is dying (without parsing the argument, which is an arbitrary string). Second, we don’t know where the program is dying without parsing the line number out of the argument (but when you think about it, that information is absolutely useless inside your program). And third, the Faustian bargain that this handler has made lasts only as long as it does; as soon as the handler exits, your program dies anyway.[7] [7] Unlike real signal handlers, which return to whatever code was executing when the signal arrived. Fortunately, there is an approach that solves two of these problems at the same time, which is to use the block form of the eval operator. Put the code you want to check on in the block, and if anything inside it causes it to die, Perl will transfer control to the end of the block and put the message from die in the special variable $@. For example, my %dotfiles; while (my ($username, $home) = (getpwent)[0,7]) { eval { opendir HOME, $home or die “$home: $!”; foreach (grep -f && /^./, readdir HOME) { open DOT, “$home/$_” or die “$_: $!”; $dotfiles{$username}{$_} = () = ; close DOT; } closedir HOME; }; # Note the semicolon that is required here if ($@) { print “Problem with $username, reason: $@”; } } Because we get to choose how much or how little code goes inside the eval block, we can determine the granularity with which we trap exceptions. This code which is building a hash-of-hashes containing line counts of dot files in users’ home directories uses evalto catch two possible exceptions (the failure to open a directory or a file, respectively) and then keeps going. To bail out as soon as we hit any problem, we would wrap the eval around the whileloop. A program will not exit if it dies for some reason while under the care of an evalblock. However, we still have to parse $@ after the block to find out why an exception occurred, if there were multiple possible causes. What’s useful about this method of exception handling is that inside the eval block, we could be calling subroutines to any depth, be deep inside a horrible mixture of our code and someone else’s libraries, and have no idea what might be going on inside them; however, if any statement in them issues a die, it will get caught by that eval block.
Note: If you are looking for best quality webspace to host and run your tomcat application check Vision tomcat hosting services

Comments are closed.