Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris

Catching warnings

by Marcello (Hermit)
on Dec 13, 2005 at 18:37 UTC ( #516377=perlquestion: print w/replies, xml ) Need Help??

Marcello has asked for the wisdom of the Perl Monks concerning the following question:


In all my modules I use $SIG{__WARN__} to log warnings in a logfile. This ensures warnings are never overlooked. However, it seems some warnings cannot be caught:

package Test; use strict; use warnings; sub new { my $this = shift; my $class = ref($this) || $this; my $self = {}; bless($self, $class); $SIG{'__WARN__'} = sub { print 'WARNING: '.$_[0]; }; return $self; } sub A { my $self = shift; warn 'This will trigger $SIG{__WARN__}'; } sub B { my $self = shift; $self->NonExistingFunction(); } my $test = Test->new(); $test->A(); $test->B();
The output is:

WARNING: This will trigger $SIG{__WARN__} at line 20. Can't locate object method "NonExistingFunction" via package "Test" at + line 26.
So the fatal error triggered when calling a non-existing method is not caught.

How can I accomplish this?

Best regards,


Replies are listed 'Best First'.
Re: Catching warnings
by friedo (Prior) on Dec 13, 2005 at 18:45 UTC
    That's not a warning, that's a fatal error. If you want to catch fatal errors, there's a few things you can do:

    1. Put a handler in $SIG{__DIE__}. You will get the fatal error message but the program will still die. (Unless you do some extra work. See the perlvar entry on %SIG for details.)

    2. Wrap your possible fatality-producing code in an eval. Any fatal error will be put in $@ which you can send to your logging function. For example:

    eval { $self->NonExistingFunction(); }; print "FATAL ERROR: $@" if $@;

      $SIG{__DIE__} did the trick.


Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://516377]
Approved by friedo
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (7)
As of 2020-05-30 13:07 GMT
Find Nodes?
    Voting Booth?
    If programming languages were movie genres, Perl would be:

    Results (172 votes). Check out past polls.