Difference between revisions of "PERL/C3/Exception-and-error-handling-in-PERL/English"

From Script | Spoken-Tutorial
Jump to: navigation, search
(Created page with "'''Title of script''':''' Exception and Error handling in PERL''' '''Author: Nirmala Venkat''' '''Keywords: Exception, Error handling, ward(), die(), eval(), gedit, video tu...")
 
 
Line 93: Line 93:
  
 
'''my( $numerator, $denominator ) = @_;'''
 
'''my( $numerator, $denominator ) = @_;'''
 +
| style="border:1pt solid #000000;padding:0.097cm;"| Here we have defined a '''function divide''' which takes two '''input parameters'''
 +
 +
i.e '''dollar numerator '''and''' dollar''' '''denominator'''
 +
 +
'''At the rate underscore '''(@_) is a '''special variable '''used to pass the '''parameter list''' to the '''function'''.
 +
 +
|-
 +
| style="border:1pt solid #000000;padding:0.097cm;"|
  
 
'''if ($denominator == 0)'''
 
'''if ($denominator == 0)'''
Line 103: Line 111:
  
 
'''}'''
 
'''}'''
 +
| style="border:1pt solid #000000;padding:0.097cm;"| If the '''denominator''' is zero, the '''die''' function will quit the script.
  
'''divide(121, 2);'''
+
It will also display the error message for the user to read.
  
'''divide(360, 4);'''
+
Else it will print the output.
  
'''divide(412, 0);'''
 
  
'''divide(525, 7);'''
+
|-
| style="border:1pt solid #000000;padding:0.097cm;"| Here we have defined a '''function divide''' which takes two '''input parameters'''
+
| style="border:1pt solid #000000;padding:0.097cm;"|  
  
i.e '''dollar numerator '''and''' dollar''' '''denominator'''
+
'''divide(121, 2);'''
  
'''At the rate underscore '''(@_) is a '''special variable '''used to pass the '''parameter list''' to the '''function'''.
+
'''divide(360, 4);'''
 +
| style="border:1pt solid #000000;padding:0.097cm;"| These are the '''function call statements'''.
  
If the '''denominator''' is zero, the '''die''' function will quit the script.
+
The first two times, the '''function''' is executed because the '''second parameter''' is not zero.
  
It will also display the error message for the user to read.
+
|-
 +
| style="border:1pt solid #000000;padding:0.097cm;"|
  
Else it will print the output.
+
'''divide(412, 0);'''
 +
| style="border:1pt solid #000000;padding:0.097cm;"| The third time, the '''denominator''' value is zero, so the '''die function''' is executed.
  
These are the '''function call statements'''.
+
|-
 +
| style="border:1pt solid #000000;padding:0.097cm;"|
  
The first two times, the '''function''' is executed because the '''second parameter''' is not zero.
+
'''divide(525, 7);'''
 
+
| style="border:1pt solid #000000;padding:0.097cm;"| The last '''divide function '''will not be executed as the '''die function '''quits the script.
The third time, the '''denominator''' value is zero, so the '''die function''' is executed.
+
 
+
The last '''divide function '''will not be executed as the '''die function '''quits the script.
+
  
 
|-
 
|-
Line 221: Line 230:
 
'''};'''
 
'''};'''
  
 +
| style="border:1pt solid #000000;padding:0.097cm;"| Here in our example,''' '''
 +
 +
'''open FILE''' invokes the''' die statement, '''if it has trouble in opening a file''' “test.dat”'''
 +
 +
|-
 +
| style="border:1pt solid #000000;padding:0.097cm;"|
 
'''if ($!) {'''
 
'''if ($!) {'''
  
Line 227: Line 242:
 
'''}'''
 
'''}'''
  
| style="border:1pt solid #000000;padding:0.097cm;"| Here in our example,''' '''
+
| style="border:1pt solid #000000;padding:0.097cm;"| '''Perl''' gives the '''system error message''' from the last '''eval''' block to the variable '''dollar exclamation( $!)'''
 
+
'''open FILE''' invokes the''' die statement, '''if it has trouble in opening a file''' “test.dat”'''
+
 
+
'''Perl''' gives the '''system error message''' from the last '''eval''' block to the variable '''dollar exclamation( $!)'''
+
  
'''Dollar exclamation( $!)''' returns the error string along with the filename and line number.
 
 
|-
 
|-
 
| style="border:1pt solid #000000;padding:0.097cm;"| Press''' Ctrl+S'''
 
| style="border:1pt solid #000000;padding:0.097cm;"| Press''' Ctrl+S'''
 
| style="border:1pt solid #000000;padding:0.097cm;"| Press '''Ctrl + S''' to save the file.
 
| style="border:1pt solid #000000;padding:0.097cm;"| Press '''Ctrl + S''' to save the file.
  
Let us execute the program
 
 
|-
 
|-
 
| style="border:1pt solid #000000;padding:0.097cm;"| Switch to terminal
 
| style="border:1pt solid #000000;padding:0.097cm;"| Switch to terminal
Line 276: Line 285:
  
 
'''my( $total, $count ) = @_;'''
 
'''my( $total, $count ) = @_;'''
 +
| style="border:1pt solid #000000;padding:0.097cm;"| Type the code as shown on the screen.
  
 +
 +
We are passing''' $total''', '''$count''' as input parameters to the '''function average'''.
 +
 +
 +
 +
 +
 +
 +
 +
|-
 +
| style="border:1pt solid #000000;padding:0.097cm;"|
 
'''if ($count == 0){'''
 
'''if ($count == 0){'''
  
Line 286: Line 307:
  
 
'''}'''
 
'''}'''
| style="border:1pt solid #000000;padding:0.097cm;"| Type the code as shown on the screen.
+
| style="border:1pt solid #000000;padding:0.097cm;"|We have a possibility of getting an error if the count is zero.
 
+
We are passing''' $total''', '''$count''' as input parameters to the '''function average'''.
+
 
+
We have a possibility of getting an error if the count is zero.
+
  
 
Here, that is handled with the '''die statement'''.
 
Here, that is handled with the '''die statement'''.
  
The error message returned from '''eval''' is displayed using '''$@''' '''( dollar at the rate)'''
+
The error message returned from '''eval''' is displayed using '''$@ ( dollar at the rate)'''
  
 
If not, it will print the '''Average''' value.
 
If not, it will print the '''Average''' value.
Line 300: Line 317:
 
|-
 
|-
 
| style="border:1pt solid #000000;padding:0.097cm;"|  
 
| style="border:1pt solid #000000;padding:0.097cm;"|  
| style="border:1pt solid #000000;padding:0.097cm;"| Let us execute the program.
+
| style="border:1pt solid #000000;padding:0.097cm;"| Press Ctrl +S to save the file.  Let us execute the program.
 
|-
 
|-
 
| style="border:1pt solid #000000;padding:0.097cm;"|  
 
| style="border:1pt solid #000000;padding:0.097cm;"|  
Line 320: Line 337:
  
 
Summary
 
Summary
| style="border:1pt solid #000000;padding:0.097cm;"| This brings us to the end of this tutorial. Let us summarise
+
| style="border:1pt solid #000000;padding:0.097cm;"| This brings us to the end of this tutorial. Let us summarise.
  
 
In this tutorial, we have learnt how to
 
In this tutorial, we have learnt how to
Line 333: Line 350:
 
| style="border:1pt solid #000000;padding:0.097cm;"| As an assignment do the following.
 
| style="border:1pt solid #000000;padding:0.097cm;"| As an assignment do the following.
  
# On your linux machine, create a file '''emp.txt''' with 5 employee names.  
+
# On your '''Linux''' machine, create a file '''emp.txt''' with 5 employee names.  
 
# Change permission of '''emp.txt '''to '''READ''' only.
 
# Change permission of '''emp.txt '''to '''READ''' only.
#:'''Note''': Go through the relevant''' Linux''' spoken tutorials on the''' spoken tutorial''' website for change permission option.
+
#:'''Note''': Go through the relevant''' Linux''' spoken tutorials on the''' spoken tutorial''' website for '''change permission''' option.
# Write a Perl program to open the '''emp.txt''' file in '''WRITE''' mode and add few employee names to it.
+
# Write a '''Perl''' program to open the '''emp.txt''' file in '''WRITE''' mode and add few employee names to it.
# Using "'''eval'''", print appropriate error message if open/write operation fails.
+
# Using "'''eval'''", print appropriate error message if '''open/write''' operation fails.
 
|-
 
|-
 
| style="border:1pt solid #000000;padding:0.097cm;"| Slide 12:
 
| style="border:1pt solid #000000;padding:0.097cm;"| Slide 12:

Latest revision as of 11:28, 8 August 2015

Title of script: Exception and Error handling in PERL

Author: Nirmala Venkat

Keywords: Exception, Error handling, ward(), die(), eval(), gedit, video tutorial


Visual Cue
Narration
Slide 1: Welcome to the Spoken Tutorial on Exception and error handling in PERL
Slide 2: In this tutorial we will learn to
  • Catch errors and
  • Handle exceptions
Slide 3: For this tutorial, I am using
  • Ubuntu Linux 12.04 operating system
  • Perl 5.14.2
  • and the gedit Text Editor

You can use any text editor of your choice.

Slide 4: To follow this tutorial, you should have working knowledge of Perl Programming.

If not, then go through the relevant Perl spoken tutorials on the spoken tutorial website.

Slide 5: When an error occurs:
  1. Exception handling deviates the execution of a program from the normal execution path.
  1. Error handling helps to recover the program, without terminating the application.
We can identify and trap an error in a number of ways.

We will see few commonly used methods in Perl.

Slide 6:

Warn() Function

Example:

chdir('/downloads') or warn “Cannot change directory”

The warn function only raises a warning message without taking further action.
Slide 7:

Die() Function

Example:

chdir('/downloads') or die “Cannot change directory”

The die function immediately terminates the execution and displays the error message.
Let us understand the die function using a sample program, which I have already saved.
Switch to the Terminal and type

gedit die.pl &

Go to the terminal and type

gedit die dot pl ampersand and press Enter

Point to the filename die.pl in the Titlebar of gedit. This is code in die.pl file.

Let us understand the code now.

#!/usr/bin/perl

sub divide {

my( $numerator, $denominator ) = @_;

Here we have defined a function divide which takes two input parameters

i.e dollar numerator and dollar denominator

At the rate underscore (@_) is a special variable used to pass the parameter list to the function.

if ($denominator == 0)

{die "Can't divide by zero!";}

else

{ print " Result: ",($numerator / $denominator),"\n";}

}

If the denominator is zero, the die function will quit the script.

It will also display the error message for the user to read.

Else it will print the output.


divide(121, 2);

divide(360, 4);

These are the function call statements.

The first two times, the function is executed because the second parameter is not zero.

divide(412, 0);

The third time, the denominator value is zero, so the die function is executed.

divide(525, 7);

The last divide function will not be executed as the die function quits the script.
Press Ctrl + S Press Ctrl + S to save the program.
Let us execute the program.
On the terminal type

perl die dot pl >> press Enter

Switch back to the terminal and type,

perl die dot pl and press Enter.

Highlight

Output

Result: 60.5

Result: 90

Can't divide by zero! at die.pl line 6.

The output is displayed as shown here.

Can't divide by zero! -

This is the error message we have given in the program in the die statement.

<<PAUSE>>

Next, we will see how to use eval function in error handling.
Slide 8:

eval() Function

eval function is used for handling run-time errors or exceptions.

For example, built-in errors such as out of memory, divide by zero or user defined errors.

Slide 9:

Syntax for eval():

eval {….}

if ($!) {

# deal with error here }

The general syntax for eval function is shown here.

The dollar exclamation($!) special variable holds the error message, if any.

Otherwise, dollar exclamation( $!) holds an empty string.

That means it is evaluated as false.

Switch to the terminal. Let us understand the eval function using a sample program.

Go to the terminal.

Type gedit eval dot pl ampersand >> press Enter Type gedit eval dot pl ampersand and press Enter
In the eval dot pl file, type the following code as displayed on the screen.

Let me explain the code now.

Example: 1

#!/usr/bin/perl

my $f = 'test.dat';

eval {

open FILE, $f

or die "Cannot open $f: $!";

};

Here in our example,

open FILE invokes the die statement, if it has trouble in opening a file “test.dat”

if ($!) {

print "An error occurred ($!) \n";

}

Perl gives the system error message from the last eval block to the variable dollar exclamation( $!)
Press Ctrl+S Press Ctrl + S to save the file.
Switch to terminal

perl eval dot pl >> press Enter

Switch back to the terminal and type,

perl eval dot pl and press Enter.

Highlight Output

An error occurred (No such file or directory)

The system error message is displayed as shown here.
Let us see another example.

This time we will see an error message returned from eval function using $@ (dollar at the rate).

Let us switch back to the eval dot pl file.
Example : 2

average(123, 5);

average(356, 41);

average(42,0);

average(500, 7);


eval { $average = $total / $count };

sub average {

my( $total, $count ) = @_;

Type the code as shown on the screen.


We are passing $total, $count as input parameters to the function average.




if ($count == 0){

die "Can't divide by zero!: $@";}

else{

print " Average: ",($total / $count),"\n";}

}

We have a possibility of getting an error if the count is zero.

Here, that is handled with the die statement.

The error message returned from eval is displayed using $@ ( dollar at the rate)

If not, it will print the Average value.

Press Ctrl +S to save the file. Let us execute the program.
Switch back to the terminal and type,

perl eval.pl and press Enter.

Highlight Output

Average: 24.6

Average: 8.68292682926829

Can't divide by zero! : at eval.pl line 15.

The output is as shown here.
Slide 10:

Summary

This brings us to the end of this tutorial. Let us summarise.

In this tutorial, we have learnt how to

  • Catch errors and
  • Handle exceptions
slide 11:

Assignment

As an assignment do the following.
  1. On your Linux machine, create a file emp.txt with 5 employee names.
  2. Change permission of emp.txt to READ only.
    Note: Go through the relevant Linux spoken tutorials on the spoken tutorial website for change permission option.
  3. Write a Perl program to open the emp.txt file in WRITE mode and add few employee names to it.
  4. Using "eval", print appropriate error message if open/write operation fails.
Slide 12:

About the Spoken Tutorial Project

The video at the following link summarises the Spoken Tutorial project.

Please download and watch it.

Slide 13:

Spoken Tutorial Workshops

The Spoken Tutorial Project Team
  • conducts workshops using spoken tutorials and
  • gives certificates on passing online tests.

For more details, please write to us.

Slide 14:

Acknowledgement

Spoken Tutorial project is funded by NMEICT, MHRD, Government of India. More information on this mission is available at this link.

This is Nirmala Venkat from IIT Bombay, signing off. Thanks for watching.

Contributors and Content Editors

Nancyvarkey, Nirmala Venkat