-1

I was wondering if the code below demonstrates a custom exception in C#?

public class NoBobException : Exception { public NoBobException() : base("No Bob's in TextBox") { } } private void BobsForm_Load(object sender, EventArgs e) { if(textbox1.text == "Bob") { throw new NoBobException(); } } 
5
  • 2
    it does. why dont you try it your self Commented Aug 8, 2015 at 13:01
  • 2
    A class derived from Exception is a custom one. Commented Aug 8, 2015 at 13:03
  • I did and it worked fine. The problem was i didn't know if this was called 'custom exception' I'm still new to this. @M.kazemAkhgary. Commented Aug 8, 2015 at 13:04
  • Thank you for the explanation @AmitKumarGhosh I really appreciate it. Commented Aug 8, 2015 at 13:05
  • 1
    A suggestion though when using custom exceptions. Name them well. Your example is confusing if I was calling your code. NoBobException is thrown when there IS a Bob? It should be NoBobAllowedException or something like that. Commented Aug 8, 2015 at 14:13

3 Answers 3

2

From this link : https://msdn.microsoft.com/en-us/library/87cdya3t(v=vs.110).aspx I quote :

If you want users to be able to programmatically distinguish between some error conditions, you can create your own user-defined exceptions. The .NET Framework provides a hierarchy of exception classes ultimately derived from the base class Exception. Each of these classes defines a specific exception, so in many cases you only have to catch the exception. You can also create your own exception classes by deriving from the Exception class.

Conclusion : deriving from Exception is all it takes.

Sign up to request clarification or add additional context in comments.

Comments

0

In the code example of this question, it is better to use an input data validation, because an exception handling in event handlers is complicated and it is better to avoid throwing exceptions in event handlers. The example of a custom exception is in my answer in a similar question Custom Exception C#.

Comments

0

As it is said in Programming C# 10.0 by Ian Griffiths:

The minimum requirement for a custom exception type is that it should derive from Exception (either directly or indirectly).

The NoBobException class is deriveed from Exception class, so it is an standard custom exception.

Comments