What is the experimental try/catch syntax in Perl?

Overview

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. Instead, the error is caught and printed by the catch block.

The general syntax for try/catch is shown below:

use Error ':try';

try
  {
    #something that fails
  } catch( Error e )
  {
    #print error
  };

As shown above, it is important to include the Error module, as try/catch is part of the Error module.

However, in the recent versions of Perl, the Error module has been broken. That is why we use the Nice::Try module instead, as it has a similar syntax to Error.

Example

An example will help you better understand try/catch. We use the Nice::Try module below. We print inside the try block and use die to catch an error in the catch block. The exception is printed inside the catch block.

use Nice::Try;
print( "Trying code" );
try
{
print( "Inside the try block" );
die( "For testing catch block!" );
}
catch( Exception $e ) {
return( "Caught an exception $e" );
}
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved