Özel durumları açıkça oluşturma
C# throw
veya Visual Basic Throw
deyimini kullanarak açıkça bir özel durum oluşturabilirsiniz. Ayrıca deyimini throw
kullanarak yakalanan bir özel durumu yeniden oluşturabilirsiniz. Hata ayıklarken daha fazla bilgi sağlamak için yeniden tasarlanmış bir özel duruma bilgi eklemek iyi bir kodlama uygulamasıdır.
Aşağıdaki kod örneği, olası FileNotFoundExceptionbir öğesini yakalamak için bircatch
try
/blok kullanır. Bloğun try
catch
ardından, veri dosyası bulunamazsa öğesini yakalayan FileNotFoundException ve konsola bir ileti yazan bir blok bulunur. Sonraki deyim, yeni FileNotFoundException bir oluşturan ve özel duruma metin bilgileri ekleyen deyimdirthrow
.
var fs = default(FileStream);
try
{
// Opens a text tile.
fs = new FileStream(@"C:\temp\data.txt", FileMode.Open);
var sr = new StreamReader(fs);
// A value is read 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
{
if (fs != null)
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
Ayrıca bkz.
Geri Bildirim
https://aka.ms/ContentUserFeedback.
Çok yakında: 2024 boyunca, içerik için geri bildirim mekanizması olarak GitHub Sorunları’nı kullanımdan kaldıracak ve yeni bir geri bildirim sistemiyle değiştireceğiz. Daha fazla bilgi için bkz.Gönderin ve geri bildirimi görüntüleyin