Share via


Throwing Exceptions

You can explicitly throw an exception using the throw statement. You can also throw a caught exception again using the throw statement. It is good coding practice to add information to an exception that is rethrown to provide more information when debugging.

The following code example uses a try/catch block to catch a possible FileNotFoundException. Following the try block is a catch block that catches the FileNotFoundException and writes a message to the console if the data file is not found. The next statement is the throw statement that throws a new FileNotFoundException and adds text information to the exception.

Imports System
Imports System.IO
Public Class ProcessFile
   
   Public Shared Sub Main()
   Dim fs As New FileStream("data.txt", FileMode.Open)
      Try
         'Opens a text file.
         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:\dev directory]", e)
      Finally
         fs.Close()
      End Try
   End Sub 'Main
End Class 'ProcessFile
[C#]
using System;
using System.IO;
public class ProcessFile
{
   public static void Main()
      {
      FileStream fs = null;
         try
            //Opens a text tile.
            {
            fs = new FileStream("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:\\dev directory]",e);
            }
         finally
            {
            fs.Close();
            }
      }
}

See Also

Using the Try/Catch Block to Catch Exceptions | Using Specific Exceptions in a Catch Block | Using the Finally Block | Exception Handling Fundamentals