Error Handling in Perl
Perl provides two builtin functions to generate fatal exceptions and warnings, that are:
- die()
- 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 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:
- Compile Time Errors
- 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.
Contact Us