A
Alvin Bruney [MVP]
Exceptions must not be used to control program flow. I intend to show that
this statement is flawed.
In some instances, exceptions may be used to control program flow in ways
that can lead to improved code readability and performance.
Consider an application that must eliminate duplicates in a list.
using system.collections;
//SETUP CODE initialize a list and provide a duplicate
using System.Collections;
ArrayList arr = new ArrayList(10);
for(int i = 0; i < 10;i++)
arr.Add(i.ToString());
//dupes
arr.Add(1.ToString());
//Exception to control program flow starts here
Hashtable ht = new Hashtable();
foreach(string str in new ArrayList(arr))
{
try
{
ht.Add(str, str);
}
catch(ArgumentException)
{
arr.Remove(str);
}
}
The algorithm essentially uses the unique constrains of the hashtable to
enforce uniqueness. Logically, the program flow is controlled by the
presence of exceptions.
This approach works well when there are minimal to moderate duplicates in
the list. The logic is also clear and concise and very efficient compared
with other contemporary
techniques to remove duplicates in a list which typically involve
duplicating and iterating a copy of the list.
Conclusion: It is not true that exceptions must not be used to control
program flow.
comments/queries/takers welcome.
--
Regards,
Alvin Bruney [Microsoft MVP ASP.NET]
[Shameless Author plug]
The Microsoft Office Web Components Black Book with .NET
Now Available @ http://www.lulu.com/owc
----------------------------------------------------------
this statement is flawed.
In some instances, exceptions may be used to control program flow in ways
that can lead to improved code readability and performance.
Consider an application that must eliminate duplicates in a list.
using system.collections;
//SETUP CODE initialize a list and provide a duplicate
using System.Collections;
ArrayList arr = new ArrayList(10);
for(int i = 0; i < 10;i++)
arr.Add(i.ToString());
//dupes
arr.Add(1.ToString());
//Exception to control program flow starts here
Hashtable ht = new Hashtable();
foreach(string str in new ArrayList(arr))
{
try
{
ht.Add(str, str);
}
catch(ArgumentException)
{
arr.Remove(str);
}
}
The algorithm essentially uses the unique constrains of the hashtable to
enforce uniqueness. Logically, the program flow is controlled by the
presence of exceptions.
This approach works well when there are minimal to moderate duplicates in
the list. The logic is also clear and concise and very efficient compared
with other contemporary
techniques to remove duplicates in a list which typically involve
duplicating and iterating a copy of the list.
Conclusion: It is not true that exceptions must not be used to control
program flow.
comments/queries/takers welcome.
--
Regards,
Alvin Bruney [Microsoft MVP ASP.NET]
[Shameless Author plug]
The Microsoft Office Web Components Black Book with .NET
Now Available @ http://www.lulu.com/owc
----------------------------------------------------------