Så här använder du try/catch-blocket för att fånga undantag
Placera kodinstruktioner som kan generera eller utlösa ett undantag i ett try
block och placera instruktioner som används för att hantera undantaget eller undantagen i ett eller flera catch
block under try
blocket. Varje catch
block innehåller undantagstypen och kan innehålla ytterligare instruktioner som behövs för att hantera den undantagstypen.
I följande exempel öppnas en StreamReader fil med namnet data.txt och hämtar en rad från filen. Eftersom koden kan utlösa något av tre undantag placeras den i ett try
block. Tre catch
block fångar undantagen och hanterar dem genom att visa resultatet för konsolen.
using namespace System;
using namespace System::IO;
public ref class ProcessFile
{
public:
static void Main()
{
try
{
StreamReader^ sr = File::OpenText("data.txt");
Console::WriteLine("The first line of this file is {0}", sr->ReadLine());
sr->Close();
}
catch (Exception^ e)
{
Console::WriteLine("An error occurred: '{0}'", e);
}
}
};
int main()
{
ProcessFile::Main();
}
using System;
using System.IO;
public class ProcessFile
{
public static void Main()
{
try
{
using (StreamReader sr = File.OpenText("data.txt"))
{
Console.WriteLine($"The first line of this file is {sr.ReadLine()}");
}
}
catch (FileNotFoundException e)
{
Console.WriteLine($"The file was not found: '{e}'");
}
catch (DirectoryNotFoundException e)
{
Console.WriteLine($"The directory was not found: '{e}'");
}
catch (IOException e)
{
Console.WriteLine($"The file could not be opened: '{e}'");
}
}
}
Imports System.IO
Public Class ProcessFile
Public Shared Sub Main()
Try
Using sr As StreamReader = File.OpenText("data.txt")
Console.WriteLine($"The first line of this file is {sr.ReadLine()}")
End Using
Catch e As FileNotFoundException
Console.WriteLine($"The file was not found: '{e}'")
Catch e As DirectoryNotFoundException
Console.WriteLine($"The directory was not found: '{e}'")
Catch e As IOException
Console.WriteLine($"The file could not be opened: '{e}'")
End Try
End Sub
End Class
CLR (Common Language Runtime) fångar undantag som inte hanteras av catch
block. Om ett undantag fångas av CLR kan något av följande resultat inträffa beroende på din CLR-konfiguration:
- En dialogruta för felsökning visas.
- Programmet stoppar körningen och en dialogruta med undantagsinformation visas.
- Ett fel skrivs ut till standardfelutdataströmmen.
Kommentar
De flesta kod kan utlösa ett undantag, och vissa undantag, till exempel OutOfMemoryException, kan utlösas av själva CLR när som helst. Även om program inte krävs för att hantera dessa undantag bör du vara medveten om möjligheten att skriva bibliotek som ska användas av andra. Förslag på när du ska ange kod i ett try
block finns i Metodtips för undantag.