Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Try::Tiny still recommended for exception handling in Perl 5.14 or later?

The consensus of the Perl community seems to be that Try::Tiny is the preferred way to handle exceptions.

Perl 5.14 (which is the version I use) seems to solve the issues with eval that Try::Tiny addresses. Will Try::Tiny still provide any benefits for me?

like image 434
Eugene Yarmash Avatar asked Apr 28 '12 15:04

Eugene Yarmash


People also ask

Does Perl have try catch?

The try and catch block of code is used for error handling in Perl, similar to other languages such as Java and Python. The try and catch block tries the code meant to be executed in the try block, and if an error occurs, the program does not crash.


1 Answers

My answer is unpopular, but I don't think Perl programmers should be trying to use the exceedingly poor notion of the thing we call "exceptions" in Perl. These are essentially a side channel return value. However, still being enamored with the idea of exceptions, even with all the complexities of using a global variable to pass around state, people keep trying to make it work.

Practically, however, people use die to signal failure. Some will say that you can die with a reference and pass back error objects, but you don't need die for that. We have objects, so we should use all the power of objects:

 sub some_sub {     ...     return Result->new( error => 1, description => ... ) if $something_went_wrong;     return Result->new( error => 0, ... );     }   my $result = some_sub( ... );  if( $result->is_error ) { ... }; 

That doesn't involve global variables, action at a distance, scoping headaches, or require special specials. You create a tiny class Result, or whatever you want to call it, to wrap your return values so you have structured data instead of single values with no identity. There's no more wondering what a return value means. Is that undef a real value or an indication of failure? Is the return value good if it's defined or if it's true? Your object can tell you these things. And, you can use the same object with die. If you're already using the object with die and using it as the return value, there's very little to recommend all the extra stuff you have to do to tolerate $@.

I talk more about this in "Return error objects instead of throwing exceptions"

However, I know that you can't help what other people do, so you still have to pretend Perl has exceptions.

like image 177
brian d foy Avatar answered Sep 26 '22 14:09

brian d foy