Computer >> 컴퓨터 >  >> 프로그래밍 >> C#

C#에서 OutOfMemoryException(메모리 부족 예외)을 캡처하는 방법

System.OutOfMemoryException은 CLR(Common Language Runtime)이 프로그램에 필요한 충분한 메모리를 할당하지 못할 때 발생하는 예외입니다. 이 예외는 System.SystemException 클래스를 상속받습니다.

아래에서는 StringBuilder의 용량(Capacity) 제한으로 인해 이 예외가 발생하는 상황을 만들고, 이를 try-catch 블록으로 안전하게 처리하는 방법을 살펴보겠습니다.

1. 문자열 변수 설정

먼저 두 개의 문자열을 준비합니다.

string StudentName = "Tom";
string StudentSubject = "Maths";

2. 용량이 고정된 StringBuilder 초기화

StringBuilder를 생성할 때 최대 용량을 초기 값의 길이와 동일하게 지정합니다.

StringBuilder sBuilder = new StringBuilder(StudentName.Length, StudentName.Length);

이렇게 하면 StringBuilder의 최대 용량이 "Tom"의 길이인 3으로 고정됩니다.

3. 용량 초과 시 예외 발생

이제 이미 가득 찬 StringBuilder에 추가 값을 삽입하려고 하면 예외가 발생합니다.

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

용량을 초과하여 메모리를 더 할당할 수 없기 때문에 다음과 같은 예외가 발생합니다.

System.OutOfMemoryException: Out of memory

4. try-catch로 예외 캡처하기

이러한 오류를 안전하게 처리하려면 try-catch 블록을 사용해야 합니다. 아래는 전체 예제 코드입니다.

예제 코드

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을 catch 블록에서 잡아내어 프로그램이 비정상 종료되지 않도록 처리합니다.

실행 결과

Error:
System.OutOfMemoryException: Out of memory

정리

OutOfMemoryException은 단순히 메모리가 물리적으로 부족할 때만 발생하는 것이 아니라, 위 예제처럼 StringBuilder의 고정된 용량을 초과하는 경우에도 발생할 수 있습니다. 실무에서는 이처럼 try-catch 블록으로 예외를 명시적으로 캡처하고, 로그를 남기거나 사용자에게 적절한 안내 메시지를 제공함으로써 프로그램의 안정성을 높일 수 있습니다.