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
ADVERTISEMENT


Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.