Exceptions handle runtime errors gracefully without crashing the program.
try {
int[] numbers = { 1, 2, 3 };
Console.WriteLine(numbers[5]); // Throws IndexOutOfRangeException
} catch (IndexOutOfRangeException ex) {
Console.WriteLine($"Error: {ex.Message}");
} catch (Exception ex) {
Console.WriteLine($"General error: {ex.Message}");
} finally {
Console.WriteLine("This runs whether or not an exception occurs");
}
class AgeException : Exception {
public AgeException(string message) : base(message) { }
}
void ValidateAge(int age) {
if (age < 0 || age > 150) {
throw new AgeException("Age must be between 0 and 150");
}
}
using (var reader = new StreamReader("file.txt")) {
string content = reader.ReadToEnd();
} // Automatically disposes the resource
try { /* code */ }
catch (Exception ex) {
Console.WriteLine(ex.Message); // Human-readable description
Console.WriteLine(ex.StackTrace); // Call stack
Console.WriteLine(ex.InnerException); // Nested exception
}
Write a C# program that applies the concepts covered in this chapter. Experiment with different inputs and test your understanding.