방법: 명시적으로 예외 Throw

업데이트: 2007년 11월

throw 문을 사용하면 예외를 명시적으로 throw할 수 있으며 catch된 예외를 throw 문을 사용하여 다시 throw할 수도 있습니다. 디버깅할 때 더 많은 정보를 제공할 수 있도록 다시 throw한 예외에는 정보를 추가하는 것이 좋은 코드 작성 방법입니다.

다음 코드 예제에서는 발생 가능한 FileNotFoundException을 try/catch 블록을 사용하여 catch합니다. try 블록의 뒤에는 데이터 파일을 찾지 못할 경우 FileNotFoundException을 catch하고 콘솔에 메시지를 표시하는 catch 블록이 있습니다. 그 다음 throw 문은 새 FileNotFoundException을 throw하고 텍스트 정보를 예외에 추가합니다.

예제

Option Strict On

Imports System
Imports System.IO

Public Class ProcessFile

   Public Shared Sub Main()
      Dim fs As FileStream = Nothing
      Try
          'Opens a text file.
          fs = New FileStream("c:\temp\data.txt", FileMode.Open)
          Dim sr As New StreamReader(fs)
          Dim line As String

          'A value is read from the file and output to the console.
          line = sr.ReadLine()
          Console.WriteLine(line)
      Catch e As FileNotFoundException
          Console.WriteLine("[Data File Missing] {0}", e)
          Throw New FileNotFoundException("[data.txt not in c:\temp directory]", e)
      Finally
          If fs IsNot Nothing Then fs.Close
      End Try
   End Sub 
End Class 
using System;
using System.IO;

public class ProcessFile
{
   public static void Main()
      {
      FileStream fs = null;
      try   
      {
         //Opens a text tile.
         fs = new FileStream(@"C:\temp\data.txt", FileMode.Open);
         StreamReader sr = new StreamReader(fs);
         string line;

         //A value is read from the file and output to the console.
         line = sr.ReadLine();
         Console.WriteLine(line);
      }
      catch(FileNotFoundException e)
      {
         Console.WriteLine("[Data File Missing] {0}", e);
         throw new FileNotFoundException(@"data.txt not in c:\temp directory]",e);
      }
      finally
      {
         if (fs != null) 
            fs.Close();
      }
   }
}

참고 항목

작업

방법: Try/Catch 블록을 사용하여 예외 catch

방법: Catch 블록에 특정 예외 사용

방법: Finally 블록 사용

기타 리소스

예외 처리 기본 사항