When executing C# code, different errors can occur: coding errors made by the programmer, errors due to wrong input, or other unforeseeable things like a file missing.
When an error occurs, C# will normally stop and generate an error message. The technical term for this is: C# will throw an exception (throw an error).
If we don't "catch" this exception, our entire application crashes!
To handle these errors gracefully, we use the try and catch statements.
try statement allows you to define a block of code to be tested for errors while it is being executed.catch statement allows you to define a block of code to be executed if an error occurs in the try block.using System;class Program { static void Main(string[] args) { try { int[] myNumbers = {1, 2, 3}; // ERROR! Array only has 3 items. Index 10 does not exist! Console.WriteLine(myNumbers[10]); } catch (Exception e) { // This block runs because an error occurred in the try block Console.WriteLine("Something went wrong."); Console.WriteLine("Error Details: " + e.Message); } } }
Without the try...catch block, the program would completely crash. With it, the program handles the error and can continue running smoothly!
finally BlockThe finally statement lets you execute code after try...catch, regardless of whether an exception occurred or not.
It is commonly used to clean up resources, like closing a file or a database connection, because you want that cleanup to happen whether the operation succeeded or failed.
using System;class Program { static void Main(string[] args) { try { int[] myNumbers = {1, 2, 3}; Console.WriteLine(myNumbers[10]); } catch (Exception e) { Console.WriteLine("Something went wrong."); } finally { Console.WriteLine("The 'try catch' is finished."); } } }
throw KeywordThe throw statement allows you to create a custom error. You can use it alongside the built-in exception classes like ArgumentException, ArithmeticException, FileNotFoundException, etc.
For example, you could check someone's age and use throw new ArgumentException("Access denied - You must be at least 18 years old."); if they are too young!
Which block lets you execute code regardless of whether an exception occurred or not?