当CLR未能分配所需的足够内存时,将发生System.OutOfMemoryException。
System.OutOfMemoryException继承自System.SystemException类。
设置字符串-
string StudentName = "Tom"; string StudentSubject = "Maths";
现在您需要使用分配的容量进行初始化,该容量是初始值的长度-
StringBuilder sBuilder = new StringBuilder(StudentName.Length, StudentName.Length);
现在,如果您尝试插入其他值,则会发生异常。
sBuilder.Insert(value: StudentSubject, index: StudentName.Length - 1, count: 1);
发生以下异常-
System.OutOfMemoryException: Out of memory
要捕获错误,请尝试以下代码-
using System; using System.Text; namespace Demo { class Program { static void Main(string[] args) { try { string StudentName = "Tom"; string StudentSubject = "Maths"; StringBuilder sBuilder = new StringBuilder(StudentName.Length, StudentName.Length); //附加初始值 sBuilder.Append(StudentName); sBuilder.Insert(value: StudentSubject, index: StudentName.Length - 1, count: 1); } catch (System.OutOfMemoryException e) { Console.WriteLine("Error:"); Console.WriteLine(e); } } } }
上面处理OutOfMemoryException并生成以下错误-
输出结果
Error: System.OutOfMemoryException: Out of memory