C# novice here, when the int 'max' below is 0 I get a divide by zero error, I can see why this happens but how should I handle this when max is 0? position is also an int.
private void SetProgressBar(string text, int position, int max)
{
try
{
int percent = (100 * position) / max; //when max is 0 bug hits
string txt = text + String.Format(". {0}%", percent);
SetStatus(txt);
}
catch
{
}
}
Well, that entirely depends on the behaviour you want. If the maximum value of your program bar is zero, is it full? Is it empty? This is a design choice, and when you've chosen, just test for max == 0 and deploy your answer.
Convert your
into
int percent = ( max > 0 ) ? (100 * position) / max : 0;
Depends on what you want.
Well, if max is zero, then there is no progress to be made. Try catching the exception where this is called. That is probably the place to decide whether there is a problem or if the progress bar should be set at zero or at 100%.
You would need a guard clause which checks for max == 0.
You could also handle the Divide by Zero exception, as your sample showed, but it is generally more costly to handle exceptions then to set up checks for known bad values.
Check for zero.