Come generare in modo esplicito le eccezioni
È possibile generare in modo esplicito un'eccezione usando l’istruzione throw
C# o l'istruzione Throw
Visual Basic. È anche possibile generare di nuovo un'eccezione rilevata usando l'istruzione throw
. Si consiglia di aggiungere informazioni a un'eccezione generata di nuovo per offrire ulteriori informazioni durante il debug.
L'esempio di codice seguente usa un blocco try
/catch
per rilevare una possibile eccezione FileNotFoundException. Il blocco try
è seguito da un blocco catch
che rileva FileNotFoundException e scrive un messaggio nella console se il file di dati non viene trovato. L'istruzione successiva è l'istruzione throw
che genera una nuova eccezione FileNotFoundException e aggiunge informazioni di testo all'eccezione.
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();
}
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