Try and Catch
Division durch Null
try
{
int a = 10;
int b = 0;
int result = a / b;
Console.WriteLine("Ergebnis: " + result);
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Division durch Null ist nicht erlaubt: " + ex.Message);
}
Convert String to Integer
bool loopint = true;
while(looping)
{
try
{
Console.Write("Enter a number: ")
int num = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("The number is: " + num);
loopint = false;
}
catch (OverflowException)
{
Console.WriteLine("Please only numbers less than 2 Billion!")
}
catch (FormatException)
{
Console.WriteLine("Please enter only numbers!");
}
catch (Exception e)
{
Console.WriteLine("Error: " + e.Message);
}
}
Datei lesen
try
{
string text = File.ReadAllText("datei.txt");
Console.WriteLine(text);
}
catch (FileNotFoundException ex)
{
Console.WriteLine("Datei nicht gefunden: " + ex.Message);
}
catch (IOException ex)
{
Console.WriteLine("Ein Fehler ist beim Lesen der Datei aufgetreten: " + ex.Message);
}