Search code examples
perlerror-handlingtry-catch

Try Catch in Perl without external library


I'm generating a Perl code from Java code and try to simulate the try catch mechanism. I cannot use external libraries. I found two possible methods to simulate this behavior:

First one:

eval {
     ...
};
if ($@) {
     errorHandler($@);
}

Second:

unless(.....){
    // handle the error
}

My knowledge in Perl is very little. As I understand, the first solution enables me to execute multiple commands while the second solution enables me to execute only 1 command. But, I also saw that using eval is not recommended.

What is the "right" way of doing it?


Solution

  • your second snippet doesn't catch exceptions at all, so it's not an option. Your options in core[1] are:

    1.  my $rv;
       if (!eval { $rv = f(); 1 } ) {
          warn($@);
       }
      
    2.  my $rv = eval { f() };
       if ($@) {
          warn($@);
       }
      

      Downside (of this second version): Before 5.14, an exception can go unnoticed if an object destructor clobbers $@.

    Outside of core,

    1. TryCatch

      use TryCatch;
      
      try {
         f();
      } catch($e) {
         warn($e);
      }
      
    2. Nice::Try

      use Nice::Try;
      
      try {
         f();
      } catch($e) {
         warn($e);
      }
      
    3. Try::Tiny

      use Try::Tiny;
      
      my $rv = try {
         f();
      } catch {
         warn($_);
      };
      

      Downside (of the Try::Tiny version): The blocks are subs in disguise, so you can't use return from within them.

    There may be others.


    1. A stupid requirement. Many useful tools aren't available in core, and modules available in core aren't necessarily the best or even recommended.