Open In App

Error Handling in Perl

Last Updated : 11 Nov, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Error Handling in Perl is the process of taking appropriate action against a program that causes difficulty in execution because of some error in the code or the compiler. Processes are prone to errors. For example, if opening a file that does not exist raises an error, or accessing a variable that has not been declared raises an error.
The program will halt if an error occurs, and thus using error handling we can take appropriate action instead of halting a program entirely. Error Handling is a major requirement for any language that is prone to errors.

Errors can be classified by the time at which they occur:

  1. Compile Time Errors
  2. Run Time Errors

Compile Time Error: It is an error such as syntax error or missing file reference that prevents the program from successfully compiling.

Run Time Error : It is an error that occurs when the program is running and these errors are usually logical errors that produce the incorrect output.

Error Handling in Perl

Perl provides two builtin functions to generate fatal exceptions and warnings, that are:

  1. die()
  2. warn()

die() : To signal occurrences of fatal errors in the sense that the program in question should not be allowed to continue.

For example, accessing a file with open() tells if the open operation is successful before proceeding to other file operations.

open FILE, "filename.txt" or die "Cannot open file: $!\n";

Note: $! is a predefined variable that returns the error message returned by the system on the error.

warn() : Unlike die() function, warn() generates a warning instead of a fatal exception.

For example:

open FILE, "filename.txt" or warn "Cannot open file: $!\n";

Other methods that can be used for handling Errors

  • if statement
  • unless function
  • Error ‘:try’ module

The if statement: The statements in a code block will be executed only if the condition holds true.

perl




if(-e $filename)){
  print "File exists";
  
} else {
  die "Cannot open the file. $!"
}


unless function : The statements in the code block will only be executed if the expression returns false.

perl




unless(-e $filename) {
   die "File Does not Exist! $!";
}


The Error ‘:try’ : It is similar to the try and catch block as in Java programming language.

perl




use Error ':try';
  
try{
  open FILE, "filename.txt" or die "File cannot be opened: $!";
  while () {
      # Do something
   }
   close FILE;
} catch Error::Simple with {
     my $err = shift;
     print "ERROR: $err";
};


Error within Modules

So far we have seen how Perl handles and informs about the errors to the programmer, but what if there was an error in a module that needs to be informed to the programmer? Such errors will cause difficulty in execution of all those codes which import that particular module.

For example, you make a module let’s say test.pm, and we are doing a wrong calculation, so an error message will be thrown as shown below:

perl




package test;
sub functionName
{
   warn "Error in module!"
}
1;


use test;
functionName();

Output:

Error in module! at test.pm line 6

This error handling technique can be used by the programmers to rectify all the errors in the module. Carp module() can be used to provide methods for reporting errors within modules.

The Carp Module

It is alternative to warn and die for modules. It is useful for user-defined modules because they act somewhat like die() and warn(), but with a message which is added by the programmer.
This Carp module provides some functions which are:

  1. carp()
  2. cluck()
  3. croak()
  4. confess()

carp() function: This function works similar to warn function and prints the message given by the user without exiting the script.
Example:

perl




package test;
use Carp;
  
sub functionName
{
   carp "Error in module!"
}
1;


use test;
functionName();

Output:

Error in module!  at test.pm line 8

cluck() function: This function produces a context which is a summary of every call in the call-stack. It follows the same process as the carp() function does but it prints a stack of all the modules that led to the call to the specific function.
Example:

perl




package Test;
use Carp qw(cluck);
  
sub function_name {
    cluck "Error in module!";
}
1;


use Test;
function_name();

Output:

Error in module! at Test.pm line 5
   Test::function_name() called at test.pl line 2

croak() function: This function is similar to die() function, except that it produces a shorter message which reports the error as being from where your module was called.
Example:

perl




package Test;
use carp;
  
sub functionName {
    croak "Error in module!";
}
1;


use Test;
functionName();

Output:

Error in module! at test.pl line 2

confess() function: This function is similar to cluck() function. It calls the die function and then prints a stack of all the modules that led to the call to the specific function.
Example:

perl




package Test;
use Carp;
  
sub functionName {
    confess "Error in module!";
}
1;


use Test;
functionName();

Output:

Error in module! at Test.pm line 5
   Test::functionName() called at test.pl line 2


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads