
- C# Basic Tutorial
- C# - Home
- C# - Overview
- C# - Environment
- C# - Program Structure
- C# - Basic Syntax
- C# - Data Types
- C# - Type Conversion
- C# - Variables
- C# - Constants
- C# - Operators
- C# - Decision Making
- C# - Loops
- C# - Encapsulation
- C# - Methods
- C# - Nullables
- C# - Arrays
- C# - Strings
- C# - Structure
- C# - Enums
- C# - Classes
- C# - Inheritance
- C# - Polymorphism
- C# - Operator Overloading
- C# - Interfaces
- C# - Namespaces
- C# - Preprocessor Directives
- C# - Regular Expressions
- C# - Exception Handling
- C# - File I/O
- C# Advanced Tutorial
- C# - Attributes
- C# - Reflection
- C# - Properties
- C# - Indexers
- C# - Delegates
- C# - Events
- C# - Collections
- C# - Generics
- C# - Anonymous Methods
- C# - Unsafe Codes
- C# - Multithreading
- C# Useful Resources
- C# - Questions and Answers
- C# - Quick Guide
- C# - Useful Resources
- C# - Discussion
What are user-defined exceptions in C#?
Like any other programming language, in C#, you can easily create a user-defined exception. User-defined exception classes are derived from the Exception class. Custom exceptions are what we call user-defined exceptions.
In the below example, the exception created is not a built-in exception; it is a custom exception −
TempIsZeroException
You can try to run the following code to learn how to create a user-defined exception in C# −
Example
using System; namespace Demo { class TestTemperature { static void Main(string[] args) { Temperature temp = new Temperature(); try { temp.showTemp(); } catch(TempIsZeroException e) { Console.WriteLine("TempIsZeroException: {0}", e.Message); } Console.ReadKey(); } } } public class TempIsZeroException: Exception { public TempIsZeroException(string message): base(message) { } } public class Temperature { int temperature = 0; public void showTemp() { if(temperature == 0) { throw (new TempIsZeroException("Zero Temperature found")); } else { Console.WriteLine("Temperature: {0}", temperature); } } }
Output
TempIsZeroException: Zero Temperature found
- Related Articles
- User-Defined Exceptions in Python
- User defined and custom exceptions in Java
- User-defined Exceptions in Python with Examples
- User-defined Exceptions in C# with Example
- How to create user defined exceptions in C#?
- What are user defined data types in C#?
- What is user-defined signal handler?
- User Defined Literals in C++
- PHP User-defined functions
- User-defined Custom Exception in C#
- Using User-Defined Variables in MySQL
- User defined bridge on Docker network
- What are checked exceptions in Java?
- What are unchecked exceptions in Java?
- What are custom exceptions in Java?

Advertisements