Error Handling in Perl

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 Erros

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, "filname.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, "filname.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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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


filter_none

edit
close

play_arrow

link
brightness_4
code

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";
};

chevron_right


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:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


use Test;
functionName();

Output:

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


My Personal Notes arrow_drop_up

Very helpful in nature, leave a like and a comment if you find my articles interesting

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.