System.StackOverflowException

System.StackOverflowException

两个类互相调用,出现这个异常,不过这只是一种可能性,参考里是另一种,其他情况Google

class A()
{
 B() b = new B();
 ...
}

class B()
{
 A() a = new A();
 ...
}


 

参考:

StackOverflowException 因执行堆栈溢出错误引发,通常在存在非常深的递归或无界递归时发生。LocallocMicrosoft 中间语言 (MSIL) 指令引发 StackOverflowException

两个类互相调用应该就是无界递归了
Summary
Represents the error that occurs when the execution stack overflows due to too many method calls.

 

Description
[ Note: StackOverflowException is thrown for execution stack overflow errors, typically in the case of a very deep or unbounded recursion.

The localloc IL instruction throws StackOverflowException.

]

 

Example
The following example demonstrates an error that causes a StackOverflowException exception.

using System;
public class StackOverflowExample {
public static void recursion() { recursion(); }
public static void Main() {
try {
recursion();
}
catch(StackOverflowException e) {
Console.WriteLine("Error caught: {0}", e);
}
}
}
The output is

Error caught: System.StackOverflowException: Exception of type System.StackOverflowException was thrown.

 

转载于:https://www.cnblogs.com/coos/archive/2006/06/15/426637.html

System.StackOverflowException 是一种常见的异常,通常在程序中出现无限递归或过深的递归调用时抛出。这个异常表示堆栈已经溢出,无法继续执行当前线程的操作。以下是一些可能的原因和解决方法: ### 可能的原因 1. **无限递归**:程序中存在无限递归调用,导致堆栈不断增长,最终溢出。 2. **过深的递归**:递归调用深度超过了堆栈的容量。 3. **错误的递归终止条件**:递归函数没有正确的终止条件,导致递归无法结束。 ### 解决方法 1. **检查递归调用**:确保递归调用有一个正确的终止条件,避免无限递归。 2. **使用迭代替代递归**:如果递归深度过大,可以考虑使用迭代(循环)来替代递归。 3. **增加堆栈大小**:在某些情况下,可以通过增加堆栈大小来解决,但这种方法并不能解决根本问题。 ### 示例 假设我们有一个简单的递归函数来计算阶乘: ```csharp public int Factorial(int n) { if (n == 0) return 1; else return n * Factorial(n - 1); } ``` 如果调用 `Factorial(-1)`,将导致无限递归,最终抛出 `System.StackOverflowException`。为了修复这个问题,我们需要确保递归调用有一个正确的终止条件: ```csharp public int Factorial(int n) { if (n < 0) throw new ArgumentException("n must be non-negative", nameof(n)); if (n == 0) return 1; else return n * Factorial(n - 1); } ``` 通过添加对负数的检查,我们可以避免无限递归。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值