You can explicitly throw an exception using the C# throw or the Visual Basic Throw statement. You can also throw a caught exception again using the throw statement. It's good coding practice to add information to an exception that's rethrown to provide more information when debugging.
The following code example uses a try/catch block to catch a possible System.IO.FileNotFoundException. Following the try block is a catch block that catches the System.IO.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 System.IO.FileNotFoundException and adds text information to the exception.
sample · csharpsamples/snippets/csharp/VS_Snippets_CLR/Exception.Throwing/CS/throw.cs1
using System;
using System.IO;
namespace Example;
public class ProcessFile
{
public static void Main()
{
// <Snippet1>
var fs = default(FileStream);
try
{
// Open a text tile.
fs = new FileStream(@"C:\temp\data.txt", FileMode.Open);
var sr = new StreamReader(fs);
// Read a value from the file and output to the console.
string? line = sr.ReadLine();
Console.WriteLine(line);
}
catch (FileNotFoundException e)
{
Console.WriteLine($"[Data File Missing] {e}");
throw new FileNotFoundException(@"[data.txt not in c:\temp directory]", e);
}
finally
{
fs?.Close();
}
// </Snippet1>
}
}sample · vbsamples/snippets/visualbasic/VS_Snippets_CLR/Exception.Throwing/VB/throw.vb1
' Visual Basic .NET Document
' <Snippet1>
Option Strict On
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)
' A value is read from the file and output to the console.
Dim line As String = sr.ReadLine()
Console.WriteLine(line)
Catch e As FileNotFoundException
Console.WriteLine($"[Data File Missing] {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
' </Snippet1>