Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Catching warnings

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

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

Hello,

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 test.pl line 20. Can't locate object method "NonExistingFunction" via package "Test" at + test.pl line 26.
So the fatal error triggered when calling a non-existing method is not caught.

How can I accomplish this?

Best regards,

Marcel

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 $@;
      Thanks,

      $SIG{__DIE__} did the trick.

      Marcel

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (3)
As of 2024-04-16 14:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found