try { // some code that may cause an exception } catch (Exception ex) { // handle the exception Console.WriteLine("An exception occurred: " + ex.Message); }
public int Divide(int num1, int num2) { if (num2 == 0) throw new DivideByZeroException(); return num1 / num2; }In this example, we define a method that divides two numbers and throws a DivideByZeroException if the second number is zero. This is an example of creating a custom exception and throwing it in the code. The System Exception class is inherited by the DivideByZeroException class.