How do you implement a basic try-catch block in a C# console application?

Responsive Ad Header

Question

Grade: Education Subject: Support
How do you implement a basic try-catch block in a C# console application?
Asked by:
73 Viewed 73 Answers

Answer (73)

Best Answer
(674)
A basic try-catch block in C# involves enclosing the code that might throw an exception within the `try` block. If an exception occurs, the code within the corresponding `catch` block is executed. For example: ```csharp try { // Code that might throw an exception int result = 10 / 0; // This will throw a DivideByZeroException Console.WriteLine("Result: " + result); } catch (DivideByZeroException ex) { // Handle the DivideByZeroException Console.WriteLine("Error: Cannot divide by zero."); Console.WriteLine("Exception Message: " + ex.Message); } ``` This structure allows you to gracefully handle potential errors and prevent the application from crashing.