C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Note: The intention of the program is to demonstrate the exception itself. After the program, we note ways to deal with the exception.
C# program that raises out-of-memory exception
class Program
{
static void Main()
{
// Attempt to create a string of 2.1 billion chars.
// ... This results in an out-of-memory error.
// ... It would require 4.2 billion bytes (4 gigabytes).
string value = new string('a', int.MaxValue);
}
}
Output
Unhandled Exception: OutOfMemoryException.
However: If you have a problem with this exception and the cause is not obvious, you can use MemoryFailPoint to help diagnose the issue.
Tip: This is useful when you have a critical computation and will require a lot of memory and want no failures during the method.
Note: The book CLR via C# by Jeffrey Richter explains the MemoryFailPoint type.
But: It happens rarely in most well-designed programs and systems with typical resources.
Finally: We noted that there exists a way to predict the OutOfMemoryException in the .NET Framework.