- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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) { }
- Related Articles
- User-defined Exceptions in Python with Examples
- What are user-defined exceptions in C#?
- User-Defined Exceptions in Python
- How to create user defined exceptions in C#?
- User defined and custom exceptions in Java
- 2D vector in C++ with user defined size
- User Defined Literals in C++
- User-defined Custom Exception in C#
- What are user defined data types in C#?
- C++ set for user defined data type?
- Select into a user-defined variable with MySQL
- MySQL ORDER BY with numeric user-defined variable?
- PHP User-defined functions
- Using User-Defined Variables in MySQL
- Set user-defined variable with table name in MySQL prepare statement?

Advertisements