User-defined Exceptions in C# with Example

CsharpProgrammingServer Side Programming

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) {
}
raja
Published on 13-Aug-2018 15:40:49
Advertisements