0

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();
       }
    }
  • 2
    it does. why dont you try it your self – M.kazem Akhgary Aug 08 '15 at 13:01
  • 2
    A class `derived` from `Exception` is a `custom` one. – Amit Kumar Ghosh Aug 08 '15 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. –  Aug 08 '15 at 13:04
  • Thank you for the explanation @AmitKumarGhosh I really appreciate it. –  Aug 08 '15 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. – dmeglio Aug 08 '15 at 14:13

2 Answers2

3

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.

Philip Stuyck
  • 7,344
  • 3
  • 28
  • 39
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#.

Sharunas Bielskis
  • 1,033
  • 1
  • 16
  • 25