当 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); // Append initial value 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
以上就是C#中如何捕获内存不足异常?的详细内容,更多请关注编程之家其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。