Studio:How do I create try blocks and catch exceptions in Perl?

From STRIDE Wiki
Jump to navigation Jump to search

To create a try block and catch exceptions, use the following technique:

eval {
    # your 'try' code goes here
};
if ($@) {
    # your 'catch' code goes here
    # $@ is a string containing the error description
}

Within the eval block, if any of these are encountered:

  • a syntax error
  • a runtime error
  • a die statement

an undefined value is returned by eval and $@ is set to the error message.

If there was no error, then $@ is guaranteed to be a null string.