linux poison RSS
linux poison Email

Perl Script: Exception handling using eval()

eval in Perl is something like try .. catch block in Java, The statement eval { ... } catches an exception that was given inside it, and after it sets the special variable $@ to be the value of the exception or undef if none was caught.

If there is a syntax error or runtime error, or a die() statement is executed, an undefined value is returned by eval(), and $@ is set to the error message. If there was no error, $@ is guaranteed to be a null string. Beware that using eval() neither silences perl from printing warnings to STDERR, nor does it stuff the text of warning messages into $@.


eval {
if ($@) {
  print "Error due to :\n $@ \n";

print " === This will always get executed. === \n";
sub cal {
  $a = 10;
  $b = 0; 
  open (OUTFILE, ">", "/home/posion/fake.txt");
  print OUTFILE $a/$b;

Error due to :
Illegal division by zero at line 17.

 === This will always get executed. ===


Post a Comment

Related Posts with Thumbnails