Perl Programming - SPLessons
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Perl Error Handling

Perl Error Handling

shape Introduction

This chapter demonstrates about the Perl Error handling will always take care of program which is used to trap the error and also handle those errors and following are the concepts covered in this chapter.
  • Error Handling

Error Handling

shape Description

Error handling Take care every time during the program these techniques trap the errors and handle those errors accordingly. There are many ways to check the errors in a program initially user need to examine the return codes of the function which are using code. If user able to handle the codes properly then most of the error handling can be achieved. System calls status will store the two special variables $? and $!. Perl Eval Eval function which is used to handle fatal errors, compile time errors, runtime errors and those errors which terminates the code at some point in time. Perl Eval function contains a block of code or an expression. Evals considers everything placed in it as a string. Consider a situation of calling a subroutine which is not defined in the script. in which, the script terminates stating "undefined subroutine &XYZ, those errors are often handled within the eval function. There are several uses of evals block; one such use is once we wish to load the module which is specific to the operating system during runtime. The code below demonstrates the divide by zero causes a fatal error which can be handled by placing the Eval block as shown below. [code] $a=5; $b=0; eval { '$result=$a/$b'; } if($@) { print "$@"; # All the error codes returned by evals will get stored in $@. } [/code] Perl Try Perl does not support a try, catch blocks and at last code blocks like other programming languages. The here user needs to use them by loading an external Perl module like Try:: Tiny; In order to use this user able to place the code in a try block and catch the error in warn block. In place of $@ used in eval Try:: Tiny uses $_. # handle errors with a catch handler. The ocde below demonstrates the Perl try as shown below. [code] try { die "Die now"; } catch { warn "caught error: $_"; # not $@ }; [/code] Carp Function Carp Function which is the equelents of warn and prints the message to STDERR without actually exiting the script and printing the script the code below demonstrates the Carp function as shown below. [code] package T; require Exporter; @ISA = qw/Exporter/; @EXPORT = qw/function/; use Carp; sub function { carp "Error in module!"; } 1; [/code] if it is called from a script which is shown in below code. [code] use T; function(); [/code] Then which will produce the following result. [code] Error in module! at test.pl line 4 [/code]

Summary

shape Key Points

  • Execution and errors are always together.
  • The program will stops the execution if any error occurs.
  • Perl Eval function can have the block of code.