Exceptions

.NET provides an exception-handling mechanism. As its name implies, this mechanism helps to take care of exceptional situations in our program. Generally, if an error occurs, then the code throws an exception that can be caught by the caller code, even if this is another module or component; that is, exceptions bubble up in the call stack. Fortunately, PerlNET provides a very easy way to work with exceptions. We use die functions and eval blocks to generate and to catch exceptions respectively.

Generating and Catching Exceptions

To generate an exception in the module or any other PerlNET program, we use the die function, passing to it a string with an error description. For example, we may set a rule for our StockItem class that class users may not pass negative ID to the constructor. If we encounter negative value for ID, we throw an exception with the appropriate message string. This is how we should change the StockItem constructor code to reflect this rule (StockItemStep6):


# Constructor definition
sub StockItem
{
   # Get REFERENCE to the object
   my $this = shift;
   my ($id, $name) = @_;
   if (defined $id)
   {
      if ($id < 0)
							{
							die "Item ID should be positive";
							}
      $this->_init(int($id), $name);
   }
   else
   {
      $this->_init(int(-1), "No Name");
   }
}

To catch an exception, we should enclose the code, where an exception may occur, inside the eval block. If we do not do so, then the .NET Framework will catch the exception and will terminate our program execution, displaying an unpleasant message to the user. If a negative value is passed to StockItem, the output will be

PerlRuntime.PerlException: Item ID should be positive at unknown in C:...StockItem.pm :
 line 65.

After printing the above message, the program exits. Obviously, this is not what we want. It is better to inform the user of an error and to continue execution if possible. Consider the following code:

use namespace "OI::Samples";

$item1 = StockItem->new(-1, "Item 1");
$item2 = StockItem->new(2, "Item 2");

Here, if we do not provide any additional code, the execution would stop when trying to create Item 1. However, we would like to let the user know that we did not create this item and move on to constructing Item 2. This can be done by using the eval blocks, as follows (you may refer to the StockClient folder to work with the sample).


#
# StockClient.pl
#
use strict;
use namespace "OI.Samples";

$| = 1;
my($item1, $item2);
my $res = eval {
							$item1 = StockItem->new(-1, "Item 1");
							};
							if (!defined $res)
							{
							print $@, "
";
							}
else
{
   print "Item was created successfully!
";
}
my $res = eval {
							$item2 = StockItem->new(2, "Item 2");
							};
							if (!defined $res)
							{
							print $@;
							}
else
{
   print "Item was created successfully!
";
}

The above program produces the following output:

PerlRuntime.PerlException: Item ID should be positive at unknown in C:DevPerlDev
StockItemNETStockItemExc.pm:line
74
Item was created successfully!

This program illustrates how we can proceed with the program execution despite that an exception occurred while creating the first stock item.

C# SAMPLE

We can easily trap exceptions that PerlNET programs generate in other .NET languages. C# uses the try and catch blocks for this purpose. Here is a simple console application written in C# (PerlNET2CS), where we handle PerlNET exceptions.


//
// PerlNET2CS.cs
//
using System;
using OI.Samples;
class PerlNET2CS
{
   static void Main(string[] args)
   {
      Console.WriteLine("Enter Item ID:");
      string strID = Console.ReadLine();
      int id = Convert.ToInt32(strID);
      Console.WriteLine("Enter Item Name:");
      string strName = Console.ReadLine();
      try
      {
         Console.WriteLine("Constructing...");
         StockItem si = new StockItem(id, strName);
         Console.WriteLine("Item was created");
      }
      catch (Exception e)
      {
         Console.WriteLine("Exception occurred:");
         Console.WriteLine(e.Message);
      }
   }
}

If PerlNET code generates an exception using the die function, the .NET environment instantiates an Exception object. This object is passed to the catch block, which follows the try block, enclosing the fragment that generated the exception. We can refer to the Exception class's various methods and properties to find out what caused it. We chose to display the Message property, which holds the string that PerlNET module passed to the die function.

The above program expects two input values: an integer for the item's ID and a string for the item's name. If the ID is negative, then we should catch an exception. Otherwise, the StockItem object is successfully constructed. Here are two sample runs:

Enter Item ID:
1
Enter Item Name:
Item 1
Constructing...
Item was created
. . . . . . . . .
Enter Item ID:
-1
Enter Item Name:
item 1
Constructing...
Exception occurred:
Item ID should be positive

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.236.174