所以,这件事发生了:
如何在try
- 块内实现这一目标?
为什么不将它转发到catch
- 块?
修改
有人指出,我可能会有递归。我这样做,我认为这不会引起问题。
完整方法如下所示:
private static GeoCoordinate ChangeLocation(GeoCoordinate location)
{
var tmp = location;
var direction = new Random().Next(0, 359);
var distance = new Random().Next(0, 5);
//Calculate movement
var vertical = Math.Sin(direction) * distance; //Sinus relation shortened
var lastAngle = 180 - 90 - (direction % 90);
var horisontal = Math.Sin(lastAngle) * distance; //Sinus relation shortened
//Add movement to location
tmp.Latitude = location.Latitude + (vertical / 10000);
tmp.Longitude = location.Longitude + (horisontal / 10000);
//If new location is outside a specific area
if (!InsidePolygon(_siteCoordinates, tmp))
{
_recursiveCounter++;
//Ninja edit: @Leppie pointed out I was missing 'tmp =':
tmp = ChangeLocation(location); //Recursive move to calculate a new location
}
//Print the amount of recursive moves
if (_recursiveCounter != 0)
Console.WriteLine($"Counter: {_recursiveCounter}");
_recursiveCounter = 0;
return tmp;
}
答案 0 :(得分:2)
从2.0开始,只能在以下情况下捕获StackOverflow异常。
- CLR正在托管环境中运行,其中主机特别允许处理StackOverflow异常
- 用户代码抛出stackoverflow异常,而不是由于实际的堆栈溢出情况(Reference)
醇>
答案 1 :(得分:1)
问题
你有一个堆栈溢出异常。使用全堆栈内存时会发生这种情况。当你有一个递归循环时,这通常会发生。所以方法A调用方法B,它调用方法C,调用方法A,调用方法B,调用方法C等等。
在此循环的某处,堆栈溢出并导致此异常。例外的地方并不重要。在你的情况下,它是Random.Next(),但它也可能发生在Console.WriteLine或其他任何地方。
StackOverflowException是一种特殊类型的异常,它不能总是通过try-catch来解决。
简而言之:它与Random.Next()或try-catch没有关系。只是尝试找到并修复递归循环。
如何解决查找递归循环
答案 2 :(得分:0)
好的 - 有很多好的建议。这是对实际错误的分解:
ChangeLocation()
的返回值(感谢@leppie)。_recursiveCounter
的值为+3000,这意味着这只是自我重复。Random()
可以有种子来生成新的起始值。由于代码运行速度非常快,因此始终会弹出相同的数字,从而导致direction
和distance
的值相同。添加种子值(Sleep
为Microsoft points out)可能是解决方案,也可能只是新的种子值。_recursiveCounter
。根本原因是Random().Next(...)
被调用太多次导致其他东西抛出异常。
var direction = new Random(DateTime.Now.Millisecond + _recursiveCounter).Next(0, 359);
var distance = new Random(DateTime.Now.Millisecond + _recursiveCounter).Next(0, 5);