C# OutOfMemoryException
Program.cs
int size = int.MaxValue; Console.WriteLine(size); string[] s = new string[size];
Output
codeaft@codeaft:~/csharp$ dotnet run 2147483647 Out of memory. codeaft@codeaft:~/csharp$
C# OutOfMemoryException
Program.cs
using System; namespace Codeaft { public class Program { public static void Main(string[] args) { Stack<int> st = new Stack<int>(int.MaxValue); } } }
Output
codeaft@codeaft:~/csharp$ dotnet run Out of memory. codeaft@codeaft:~/csharp$
C# program to handle the OutOfMemoryException
Program.cs
int size = int.MaxValue; try { string[] s = new string[size]; } catch (OutOfMemoryException e) { Console.WriteLine("Array overflow"); Console.WriteLine(e.Message); }
Output
codeaft@codeaft:~/csharp$ dotnet run Array overflow Array dimensions exceeded supported range. codeaft@codeaft:~/csharp$
Comments and Reactions