miércoles, 6 de febrero de 2013

Perl: Exception Handling In Perl

Manejo de Excepciones en Perl 5


En Perl 5 se suele usar excepciones mediante "la vieja escuela" (la forma tradicional o nativa), pero también se puede usar el estilo try-catch (estilo Java) usando la librería Try::Tiny.

1) Manejo de excepciones con la vieja escuela.

#This is perl 5, version 14, subversion 2 (v5.14.2)
#!/usr/bin/perl
#Example 1: Exception Handling In Perl

#How to Handle Exception In Perl?
#perl 5, version 14, subversion 2 (v5.14.2)

use Scalar::Util qw(blessed);

# Start main
local $@; #exception


eval { #=try
     print "Doing... \n";
     die MyException->new( msg => "mensaje" )  # throw exception
};
$exception=$@;
if ($exception) { #=catch
      if (blessed($exception) && $exception->isa("MyException")) {
          print "Handle specific exception  \n";
          print $exception->get_msg;
      }
      else {         
          print "Handle all other possible exceptions \n";
      }
}

print "end \n";
# End main

# Start The exception class
package MyException;
  sub new
  {
      my $class = shift;
      bless { msg=>"@_" }, $class;
  }
  sub get_msg
  {
      my ($self) = @_;
      return sprintf "Exception: %s\n", $self->{msg};
  }
1;
# End The exception class



2) Manejo de excepciones con Try::Tiny.

#This is perl 5, version 14, subversion 2 (v5.14.2)
#File: script_test_exception.pl
#!/usr/bin/perl
use strict;
use warnings;
use Try::Tiny; #Módulo para excepciones try catch

try {
        #Bloque de código
die 'foo'; #lanza exception
} catch {
my $exception = $_;  #captura exception
warn "Message: $exception";
} finally {
print "Doing finally...";
};

=pod
Imprime en pantalla:
Message: foo at C:\Users\usuario\Documents\dario\Perl\script_NameStr.pl line 9.
Doing finally...
=cut



References:
-Exception Handling In Perl.
-Blog: Exceptions in Perl 5.
-Exceptions with (Try-Catch) Try::Tiny.