×

C# Tutorial

Basics of .Net

C# Basics

C# Fundamentals

C# Operators

C# Loops

C# Type Conversions

C# Exception Handling

C# String Class

C# Arrays

C# List

C# Stack

C# Queue

C# Collections

C# Character Class

C# Class and Object

C# Namespaces

C# Delegates

C# Constructors

C# Inheritance

C# Operator Overloading

C# Structures

C# File Handling

C# Convert.ToInt32()

C# Int32 (int) Struct

C# DateTime Class

C# Uri Class

C# Database Connectivity

C# Windows

C# Other Topics

C# Q & A

C# Programs

C# Find O/P

Home » C#

User Defined Exceptions in C#

C# User defined exceptions: In this tutorial, we are going to learn how to create user-defined exceptions in C# with examples?
Submitted by IncludeHelp, on September 21, 2019

C# User-defined exceptions

In C#, we can create our exception class by inheriting base class Exception. Because as we know that Exception is the base class for all types of exceptions in C#.

Here is the example of a user-defined exception,

using System;

class UserDefineException: Exception
{

    public UserDefineException(string str)
    {
        Console.WriteLine(str);
    }
}

class Program
{
    static void Main()
    {
        UserDefineException M = new UserDefineException("User Define Exception");

        try
        {
            throw M;
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
    }
}

Output

User Define Exception
Exception of type 'UserDefineException' was thrown. 

In the above program, we created a class "UserDefineException" by inheriting the base class "Exception" and created a parameterized constructor, through the user-defined object in "try block" of "Program" class, it is caught in "catch block".

Read more:

Advertisement
Advertisement


Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

Copyright © 2025 www.includehelp.com. All rights reserved.