奇怪的除零错误

时间:2016-04-22 03:44:09

标签: c# exception

好吧,我试图计算一条线的斜率,当然,当一个点变得未定义时,你试图除以零。好吧,我在try catch中处理这个问题,但仍然得到零错误的除法,但是在一个相当......意想不到的地方......

以下是代码:

private void tmrEnemyMovement_Tick(object sender, EventArgs e) {
        for (int i = 0; i < enemies.Count; i++) {
            int eneX = enemies[i].GetEnemyWorldPosX();
            int eneY = enemies[i].GetEnemyWorldPosY();
            int playerX = player.GetPlayerWorldPosX();
            int playerY = player.GetPlayerWorldPosY();

            double slope = -100000000;
            try {
                slope = (GetDistanceBetween(eneY, playerY)) / (GetDistanceBetween(eneX, playerX));
            } catch (DivideByZeroException) {//Division by Zero Exception is handled here.
                slope = GetDistanceBetween(eneY, playerY) / 1;
            }

            int multiplicative = 1;

            int rise = 1;//Convert.ToInt32(slope * multiplicative);
            int run = multiplicative;
            Text = Convert.ToSingle(slope) + "";

            if (enemies[i].GetEnemyWorldPosX() < player.GetPlayerWorldPosX() && enemies[i].GetEnemyWorldPosY() > player.GetPlayerWorldPosY()) {//Enemy Resides in Quadrant 2
                enemies[i].MoveEnemyTo(run, rise, "+-");
            } else if (enemies[i].GetEnemyWorldPosX() < player.GetPlayerWorldPosX() && enemies[i].GetEnemyWorldPosY() < player.GetPlayerWorldPosY()) {//Enemy Resides in Quadrant 3
                enemies[i].MoveEnemyTo(run, rise, "+-");
            } else if (enemies[i].GetEnemyWorldPosX() > player.GetPlayerWorldPosX() && enemies[i].GetEnemyWorldPosY() > player.GetPlayerWorldPosY()) {//Enemy Resides in Quadrant 1
                enemies[i].MoveEnemyTo(run, rise, "-+");
            } else if (enemies[i].GetEnemyWorldPosX() > player.GetPlayerWorldPosX() && enemies[i].GetEnemyWorldPosY() < player.GetPlayerWorldPosY()) {//Enemy Resides in Quadrant 4
                enemies[i].MoveEnemyTo(run, rise, "--");
            }
        }
        Bitmap bmp = map.GetMap() as Bitmap;

        using (Graphics drawEnemy = Graphics.FromImage(bmp)) {
            for (int i = 0; i < enemies.Count; i++) {
                drawEnemy.DrawImage(enemies[i].getSprite(), new PointF(enemies[i].GetEnemyWorldPosX(), enemies[i].GetEnemyWorldPosY()));
            }
        }
    }

由于一些奇怪的原因,我在一个奇怪的地方得到这个并不能真正帮助我:picture

此方法定义如下:

private int WorldPositionY = 0;

public int GetEnemyWorldPosY() {
    return WorldPositionY;
}

正如你所看到的,它是一个简单的getter,所以为什么我在一个try错误#1中处理除零错误#1,在这一行中处理#2? 我错过了什么吗?

**编辑:** 这是堆栈跟踪: enter image description here

1 个答案:

答案 0 :(得分:4)

尝试重新编译程序并确保您处于调试模式。也不要使用try / catch来计算斜率 - 这个声明非常长。使用

var distanceX = GetDistanceBetween(eneX, playerX);
if (distanceX != 0)
    slope = GetDistanceBetween(eneY, playerY) / distanceX;
else
    slope = GetDistanceBetween(eneY, playerY);

你抓到的这个例外并不重要。您可以按继续并继续。或者您可以关闭已处理的异常(取消选中Debug-&gt; Exceptions-&gt; Common Language Runtime中的用户处理)。或者您可以在没有附加调试器的情况下运行程序(使用Ctrl + F5)。