Divide by zero error, how do I fix this?

Scott picture Scott · Oct 2, 2008 · Viewed 39k times · Source

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
        {
        }
    }

Answer

Simon picture Simon · Oct 2, 2008
int percent = 0
if (max != 0) percent = (100*position) / max