Sunday, April 11, 2010

Use of Exception Handling

Using Exception Handling

using System;
using System.Collections;

class ExceptionsSample
{
static void Main( string[] args )
{
try
{

// Create a container to hold employees

Employees employees = new Employees(4);

// Add some employees

addOneEmployee ( employees, "Timothy", "Arthur",
"Tucker", "555-55-5555" );
addOneEmployee ( employees, "Sally", "Bess",
"Jones", null );
addOneEmployee ( employees, "Jeff", "Michael",
"Simms", "777-77-7777" );
addOneEmployee ( employees, "Janice", "Anne",
"Best", "9888-88-88889" );
// Display the employee list on screen
foreach ( Employee employee in employees )
{
string name = employee.FirstName + " " +
employee.MiddleName + " " + employee.LastName;
string ssn = employee.SSN;
Console.WriteLine( "Name: {0}, SSN: {1}", name, ssn );
}
}
catch ( Exception exception )
{
// Display any errors on screen
Console.WriteLine( exception.Message );
}
}
// Helper method to add an employee to the list
static void addOneEmployee( Employees employees,
string FirstName, string MiddleName, string LastName,
string SSN )
{
bool addedEmployee = false;
try
{
Console.WriteLine( "Adding an employee" );

if ( SSN == null )
throw new ArgumentNullException( "SSN is null!" );

if ( SSN.Length != 11 )
throw new ArgumentOutOfRangeException(
"SSN length invalid!" );

employees[employees.Length] = new Employee ( FirstName,
MiddleName, LastName, SSN );
addedEmployee = true;
}
catch ( ArgumentOutOfRangeException exception )
{
Console.WriteLine( "We caught ArgumentOutOfRangeException" );
Console.WriteLine( exception.Message );
}
catch ( ArgumentNullException exception )
{
Console.WriteLine( "We caught ArgumentNullException" );
Console.WriteLine( exception.Message );
}
catch ( Exception exception )
{
Console.WriteLine( "We caught a base exception" );
Console.WriteLine( exception.Message );
}
catch
{
Console.WriteLine( "We caught an unknown exception" );
Console.WriteLine( "Unknown exception caught!" );
}
finally
{
if ( addedEmployee == true )
Console.WriteLine( "Add was successful\r\n" );
else
Console.WriteLine( "Add failed\r\n" );
}