User-defined Exceptions in C# with Example


An exception is a problem that arises during the execution of a program. A C# exception is a response to an exceptional circumstance that arises while a program is running, such as an attempt to divide by zero.

Define your own exception. User-defined exception classes are derived from the Exception class.

The following is an example −

Example

using System;

namespace UserDefinedException {
   class TestFitness {
      static void Main(string[] args) {
         Fitness f = new Fitness();
         try {
            f.showResult();
         } catch(FitnessTestFailedException e) {
            Console.WriteLine("User defined exception: {0}", e.Message);
         }
         Console.ReadKey();
      }
   }
}

public class FitnessTestFailedException: Exception {
   public FitnessTestFailedException(string message): base(message) {
   }
}

public class Fitness {
   int points = 0;

   public void showResult() {
     
      if(points < 110) {
         throw (new FitnessTestFailedException("Player failed the fitness test!"));
      } else {
         Console.WriteLine("Player passed the fitness test!");
      }
   }
}

Above, we created a user-defined exception −

public class FitnessTestFailedException: Exception {
   public FitnessTestFailedException(string message): base(message) {
}

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 21-Jun-2020

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements