Exception objects

Matts on 2002-07-08T21:19:43

While writing my talk on Exceptions for OSCon, of course I'm talking about exception objects. Now I like to check that what I'm talking about is accurate, so I write little perl scripts for the example code I'm running.

I started to talk about how when you're throwing exception objects, you have to check ref($@) first (or blessed($@) if you have Scalar::Util available), before you check $@->isa() [*].

use strict;
eval {
die "failed\n";
};
if ($@) {
  if ($@->isa('Foo')) {
    warn("got foo\n");
  }
  else {
    warn("got $@\n");
  }
}


Of course I tested this, and discovered it's not true! When you test $string->isa() it just tries to convert $string to a package name, and checks the isa() sub in that package, which inherits from UNIVERSAL. So it doesn't actually fail. Even under -w and use strict, since calling methods on a string isn't a strict operation (and so it shouldn't be).

So does anyone know where I got this idiom from? I know I've been doing it for years, at least since I was working on both WebBoard (with O'Reilly) and on AxKit.

[*] Yes, I'm aware of UNIVERSAL::isa - I just consider it a pain to type ;-)


Hmm...

autarch on 2002-07-08T22:02:11

I think you may have gotten that from me when we worked on WebBoard.

One thing that could have caused it is if we were doing this:

  eval {  ... };

  if ( $@->isa(...) )

That'll fail if $@ is undef, which may have led us (or me) to start using UNIVERSAL::isa or something like that.