How can I prevent my perl script from terminating if an exception is thrown in a module it uses?

I have a perl script, using standard-as-dirt Net::HTTP code, and perl 5.8.8. I have come across an error condition in which the server returns 0 bytes of data when I call:

$_http_connection->read_response_headers;

Unfortunately, my perl script dies, because the Net::HTTP::Methods module has a "die" on line 306:

Server closed connection without sending any data back at
/usr/lib/perl5/vendor_perl/5.8.8/Net/HTTP/Methods.pm line 306

And lines 305-307 are, of course:

unless (defined $status) {
die "Server closed connection without sending any data back";
}

How can I have my script "recover gracefully" from this situation, detecting the die and subsequently going into my own error-handling code, instead of dieing itself?

I'm sure this is a common case, and probably something simple, but I have not come across it before.

Answers


You can use eval { } to catch die() exceptions. Use $@ to inspect the thrown value:

eval {
    die "foo";
};
print "the block died with $@" if $@;

See http://perldoc.perl.org/functions/eval.html for details.


Using eval to catch exceptions can occasionally be problematic, especially pre 5.14. You can use Try::Tiny.


Need Your Help

Java for Software Developers

java development-environment

I am a .NET developer (and have been for a while now). I work for an organization that was just recently acquired by a larger company whose primary development language is Java. There are a few .NET

Sending rails errors to rspec output

ruby-on-rails logging rspec integration-testing capybara

I am using Capybara in combination with rspec for integration testing of rails apps.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.