How to catch out of memory exception in C#?

PHPz
Release: 2023-09-05 16:09:07
forward
1044 people have browsed it

How to catch out of memory exception in C#?

System.OutOfMemoryException occurs when the CLR cannot allocate enough memory required.

System.OutOfMemoryException inherits from the System.SystemException class.

Setting up the string -

string StudentName = "Tom";
string StudentSubject = "Maths";
Copy after login

Now you need to initialize with the allocated capacity i.e. the length of the initial value -

StringBuilder sBuilder = new StringBuilder(StudentName.Length, StudentName.Length);
Copy after login

Now if you try to insert an additional value then An exception will occur.

sBuilder.Insert(value: StudentSubject, index: StudentName.Length - 1, count: 1);
Copy after login

The following exception occurred -

System.OutOfMemoryException: Out of memory
Copy after login

To catch the error, try the following code -

Example

Live Demo

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);
         }
      }
   }
}
Copy after login

Above Handles the OutOfMemoryException and generates the following error -

Output

Error:
System.OutOfMemoryException: Out of memory
Copy after login

The above is the detailed content of How to catch out of memory exception in C#?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!