Broad Network


Trying and Catching Exceptions in Perl

Perl eval Function and Error Checking Part 2

Perl Course

Foreword: In this part of the series I explain the new way to handle errors.

By: Chrysanthus Date Published: 23 Nov 2015

Introduction

This is part 2 of my series, Perl eval Function and Error Checking. In this part of the series I explain the new way to handle errors. You should have read the previous part of the series before coming here, as this is a continuation.

Programming Errors
There are three types of programming errors. In other words, there are three types of errors that can occur in a program. You have Syntax Errors, Logic Errors and Runtime Errors.

Syntax Errors
This is the wrong use of syntax. These errors are wrong statements. When you type a statement, which is wrong, that is a syntax error. Such a statement cannot be executed. For example, in a statement you can type a variable without the $ sign. Under this condition, your program does not work. Depending on how you configure your Perl installation, such an error might be indicated by Perl to the output device just before the program is to be executed, when you give a command to run the program. With a syntax error, the program is not executed.

Logic Errors
In this case, Perl understands your program very well; the program is executed. However, the program will not do what you wanted it to do. It will do something slightly different or completely different. The fault is yours. For example, a loop that is required to do 10 iterations might do 5 iterations, because you coded it mistakenly to do 5 iterations. Another example is that a loop might iterate infinitely, because the condition you gave for the loop made it that way. Logic Errors occur when the program is being executed. The only way to solve this problem is to test your program very well before you hand it to the customer (who asked for it).

Runtime Errors
Runtime errors occur when the program is being executed as a result of the fact that you did not take certain factor into consideration when coding. For example, let us say your code is to divide 8 by some denominator that the user inputs. If the user inputs 2, the division will work, giving you 4 as answer. If the user inputs zero, the division will not work, because 8/0 is undefined. When a runtime error occurs your program normally crashes (and stops). To solve runtime errors, you have to write extra code that will prevent the execution of the particular code segment or statement from taking place, under certain conditions. In this division example, you have to write code that will prevent division by zero from taking place, and possibly informing the user of the mistake he made by inputting zero as a denominator.

Preventing Runtime Errors
The following code illustrates how to prevent the above error (division by zero).

use strict;

my $numerator = 8;
my $denominator = 2;

        if ($denominator != 0 )
         {
                my $answer = $numerator/$denominator;
                print $answer;
         }
        else
         {
                print "Division by zero is not allowed!";
         }

The particular code segment here is that of the if-block. Read and try the above code if you have not done so. The code should be self-explanatory. Change the value of the denominator from 2 to 0 and try the code again.

Trying and Catching
The two main syntaxes for the eval function are:

    eval EXPR

and

    eval BLOCK;

Now, for both syntaxes, if there is a syntax error or runtime error, or a die statement is executed, eval returns undef in scalar context or an empty list in list context, and the special variable, $@ is set to the error message. If there is no error, $@ is set to the empty string.

The modern way to code error is to place the code that can have runtime error in the eval block. Under this condition, this block is called the try block. Any error message from the eval block goes to the special variable, $@. This is a scalar variable. This error message can be treated (displayed) in an anonymous block called the catch block. The above code is rewritten as follows:

use strict;

my $numerator = 8;
my $denominator = 0;

    eval  #try
        {
            my $answer = $numerator/$denominator;
            print $answer;
        };
       #catch
        {
            print $@;
        }

I tried the code and I had,

    Illegal division by zero at C:\temp.pl line 8.

Well, you can still use the $@ variable without the anonymous block. I have used the block just to make similarity with other languages.

Caution: Use this try-catch error scheme only in your main Perl program. Do not use it in a module, until the developers of Perl say it is safe for us to do so. For now, it is safe to use it in your main program such as the one above but not in a module. You can use the eval BLOCK in a module, but not to catch exception (error).

That is it for this part of the series.

Chrys

Related Links

Perl Basics
Perl Data Types
Perl Syntax
Perl References Optimized
Handling Files and Directories in Perl
Perl Function
Perl Package
Perl Object Oriented Programming
Perl Regular Expressions
Perl Operators
Perl Core Number Basics and Testing
Commonly Used Perl Predefined Functions
Line Oriented Operator and Here-doc
Handling Strings in Perl
Using Perl Arrays
Using Perl Hashes
Perl Multi-Dimensional Array
Date and Time in Perl
Perl Scoping
Namespace in Perl
Perl Eval Function
Writing a Perl Command Line Tool
Perl Insecurities and Prevention
Sending Email with Perl
Advanced Course
Miscellaneous Features in Perl
Perl Two-Dimensional Structures
Advanced Perl Regular Expressions
Designing and Using a Perl Module
More Related Links
Perl Mailsend
PurePerl MySQL API
Perl Course - Professional and Advanced
Major in Website Design
Web Development Course
Producing a Pure Perl Library
MySQL Course

BACK

Comments

Become the Writer's Fan
Send the Writer a Message