Re: Exception handling suggestions



First off,

We should try and avoid exceptions where possible

And as far as int parsing try something like this

#region isInteger
/// <summary>
/// Determines if it is a valid integer.
/// </summary>
/// <param name="var"></param>
/// <returns></returns>
public static bool isInteger(string var)
{
double result;

return (Double.TryParse(var,
System.Globalization.NumberStyles.Integer,
System.Globalization.NumberFormatInfo.CurrentInfo,
out result));
}
#endregion

#region -- intFromString --
/// <summary>
/// Safely casts a string as integer. If the string is not a valid
int NOT_INITIALISED_INT is returned.
/// </summary>
/// <param name="var">string to attempt parse on</param>
/// <param name="iDefault">int - Default to use if the string is not
a valid int</param>
/// <returns>int</returns>
public static int intFromString( string var )
{
return intFromString( var, NOT_INITIALISED_INT );
}

/// <summary>
/// Safely casts a string as integer. If the string is not a valid
int the default value is used.
/// </summary>
/// <param name="var">string to attempt parse on</param>
/// <param name="iDefault">int - Default to use if the string is not
a valid int</param>
/// <returns>int</returns>
public static int intFromString( string var, int iDefault )
{
if( isInteger( var ) )
{
return int.Parse( var );
}

return iDefault;
}
#endregion

That should get you by safely.
And if you care to test that over 100k iterations against a try catch
you will see why it is worth the effort.

On the error handling front,
In a web application we use a HttpModule with a configurable level of
reporting

This allows us to essential switch it up to maximum reporting level
during the first phase of deployment.
This is obviously slower and puts a greater load on the server, but
allows us to track and remove bugs.

This is only my opinion
After 10 years of developing commercial systems that interact with 3rd
parties I have to say that exceptions
are unavoidable but predictable. You should not be looking to trap
developer errors, these should be caught and fixed during
UAT ( this also goes if you are writing libray code for other
people ).
Rather you should be looking to cater for errors in comms failure
between your external interfaces and 3rd party software
(this includes importing files )

Hope this helps

.



Relevant Pages


Quantcast