How to handle exceptions using try-catch?

In C#, exceptions can be handled using the try-catch block.

Example:


  try 
  {
      int result = 10 / 0;
  } 
  catch (DivideByZeroException e) 
  {
      Console.WriteLine(e.Message);
  }
  

Solution:

The try block contains the code that might throw an exception, and the catch block contains the code to execute if an exception occurs:


  Console.WriteLine('Exception handled.');
  

Beginner's Guide to C#