csharp / beginner
Snippet
Basic Exception Handling
Try-catch blocks are used to handle errors (exceptions) gracefully. The code in the 'try' block runs, and if an error occurs, the 'catch' block handles it instead of crashing the program.
snippet.csharp
1
2
3
4
5
try {int result = 10 / 0;} catch (DivideByZeroException ex) {Console.WriteLine("Error: You cannot divide by zero!");}
Breakdown
1
try { ... }
Contains the code that might potentially cause an error.
2
catch (DivideByZeroException ex)
Specifically catches errors related to division by zero.