- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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) { }
Advertisements