Tuesday, October 20, 2009

Exception Handling: Part 05 of 05

Part 5: Exception Handling Best Practices

Target Audience: This pitch would interest a developer interested in the Exception Handling Best Practices in Perl. This series starts with basic exception handling and adds complexity, ending with pragmatic Best Practices recommendation.

You have put up with a lot so far and here is where it all becomes worthwhile. Best Practices, in a numbered list. Now, how much is that worth to you? (I accept checks.)

  • Use Exception::Class. Enuf said!
  • Use Fatal.pm for core perl functions:
eval { open(FH, "/non-existent/file") };
warn($@) if $@;
eval { close(FH) };
warn($@) if $@;
eval { chdir("gobbledegook") };
warn($@) if $@;
eval { unlink("/etc/password") };
warn($@) if $@;
eval { socket(SOCK, AF_INET, SOCK_STREAM, getprotobyname('tcp')) };
warn($@) if $@;
  • Define a $SIG{__DIE__} to turn string exceptions into objects
  • Trap exceptions using the 'eval' block and conditions set on the special variable $@
  • ALLOW EXCEPTIONS TO PROPAGATE!
  • Handle only an exception of an expected type.
  • To log all exceptions, use main() wrapped in exception handler.
  • Use Fatal qw(:void) in Perl 5.6+
~ * ~

All code in this series may be downloaded from:
http://sites.google.com/site/sanjaybhatikar/codeunquote/exceptionhandling-1

No comments:

Post a Comment