Know-How für Ihr Projekt

Perl Documentation



Try::Tiny - Minimal try/catch with proper preservation of $@


version 0.28


You can use Try::Tiny's try and catch to expect and handle exceptional conditions, avoiding quirks in Perl and common mistakes:

# handle errors with a catch handler
try {
  die "foo";
} catch {
  warn "caught error: $_"; # not $@

You can also use it like a standalone eval to catch and ignore any error conditions. Obviously, this is an extreme measure not to be undertaken lightly:

# just silence errors
try {
  die "foo";


This module provides bare bones try/catch/finally statements that are designed to minimize common mistakes with eval blocks, and NOTHING else.

This is unlike TryCatch which provides a nice syntax and avoids adding another call stack layer, and supports calling return from the try block to return from the parent subroutine. These extra features come at a cost of a few dependencies, namely Devel::Declare and Scope::Upper which are occasionally problematic, and the additional catch filtering uses Moose type constraints which may not be desirable either.

The main focus of this module is to provide simple and reliable error handling for those having a hard time installing TryCatch, but who still want to write correct eval blocks without 5 lines of boilerplate each time.

It's designed to work as correctly as possible in light of the various pathological edge cases (see "BACKGROUND") and to be compatible with any style of error values (simple strings, references, objects, overloaded objects, etc).

If the try block dies, it returns the value of the last statement executed in the catch block, if there is one. Otherwise, it returns undef in scalar context or the empty list in list context. The following examples all assign "bar" to $x:

my $x = try { die "foo" } catch { "bar" };
my $x = try { die "foo" } || "bar";
my $x = (try { die "foo" }) // "bar";
my $x = eval { die "foo" } || "bar";

You can add finally blocks, yielding the following:

my $x;
try { die 'foo' } finally { $x = 'bar' };
try { die 'foo' } catch { warn "Got a die: $_" } finally { $x = 'bar' };

finally blocks are always executed making them suitable for cleanup code which cannot be handled using local. You can add as many finally blocks to a given try block as you like.

Note that adding a finally block without a preceding catch block suppresses any errors. This behaviour is consistent with using a standalone eval, but it is not consistent with try/finally patterns found in other programming languages, such as Java, Python, Javascript or C#. If you learnt the try/finally pattern from one of these languages, watch out for this.


All functions are exported by default using Exporter.

If you need to rename the try, catch or finally keyword consider using Sub::Import to get Sub::Exporter's flexibility.


There are a number of issues with eval.

Clobbering $@

When you run an eval block and it succeeds, $@ will be cleared, potentially clobbering an error that is currently being caught.

This causes action at a distance, clearing previous errors your caller may have not yet handled.

$@ must be properly localized before invoking eval in order to avoid this issue.

More specifically, $@ is clobbered at the beginning of the eval, which also makes it impossible to capture the previous error before you die (for instance when making exception objects with error stacks).

For this reason try will actually set $@ to its previous value (the one available before entering the try block) in the beginning of the eval block.

Localizing $@ silently masks errors

Inside an eval block, die behaves sort of like:

sub die {
  $@ = $_[0];

This means that if you were polite and localized $@ you can't die in that scope, or your error will be discarded (printing "Something's wrong" instead).

The workaround is very ugly:

my $error = do {
  local $@;
  eval { ... };
die $error;

$@ might not be a true value

This code is wrong:

if ( $@ ) {

because due to the previous caveats it may have been unset.

$@ could also be an overloaded error object that evaluates to false, but that's asking for trouble anyway.

The classic failure mode is:

sub Object::DESTROY {
  eval { ... }
eval {
  my $obj = Object->new;
  die "foo";
if ( $@ ) {

In this case since Object::DESTROY is not localizing $@ but still uses eval, it will set $@ to "".

The destructor is called when the stack is unwound, after die sets $@ to "foo at line 42\n", so by the time if ( $@ ) is evaluated it has been cleared by eval in the destructor.

The workaround for this is even uglier than the previous ones. Even though we can't save the value of $@ from code that doesn't localize, we can at least be sure the eval was aborted due to an error:

my $failed = not eval {
  return 1;

This is because an eval that caught a die will always return a false value.


Using Perl 5.10 you can use "Switch statements" in perlsyn.

The catch block is invoked in a topicalizer context (like a given block), but note that you can't return a useful value from catch using the when blocks without an explicit return.

This is somewhat similar to Perl 6's CATCH blocks. You can use it to concisely match errors:

try {
  require Foo;
} catch {
  when (/^Can't locate .*?\.pm in \@INC/) { } # ignore
  default { die $_ }




I gave a lightning talk about this module, you can see the slides (Firefox only):

Or read the source:


Bugs may be submitted through the RT bug tracker (or




This software is Copyright (c) 2009 by יובל קוג'מן (Yuval Kogman).

This is free software, licensed under:

The MIT (X11) License