How to write your own exception in a separate class and call it when needed? Thank you in advance!

Can you describe what and where to enter? I'm still new and do not really understand. Here is the exception itself, it checks if the vector is zero (v1 and v2 are vectors, and len1 and len2 are their lengths):

//exeption try { len1 = v1.Length(); len2 = v2.Length(); if (len1 == 0 || len2 == 0) { throw new Exception("Вектор не может быть нулевым"); } } catch (Exception e) { Console.WriteLine("\nОшибка: " + e.Message); test = 10; } 
  • If you are given an exhaustive answer, mark it as correct (a daw opposite the selected answer). - Nicolas Chabanovsky

3 answers 3

In order to create your own exception, you need to create a class and inherit it from one of the types of exceptions, depending on your needs. Most often, own exceptions simply inherit from the Exception class.

Further, in order for your exception to conform to generally accepted standards, you need to have at least three constructors: by default (without parameters), a constructor with a message, a constructor with a message and an original exception. The latter can theoretically be omitted, but it is mandatory if you "wrap" some systemic exception with your exception.

(For advanced ones: if an exception will be passed across borders, then a constructor must be included for serialization. Details in the FxCop rule.)

In addition, you are free to include in the exception any additional information that may help the code processing your exception to make the necessary decision.

Total:

 [Serializable] // опционально public class GoodException : Exception { public GoodException() { // ... } public GoodException(string message) : base(message) { // ... } public GoodException(string message, Exception innerException) : base (message, innerException) { // ... } // опционально protected GoodException(SerializationInfo info, StreamingContext context) : base(info, context) { // логика сериализации } public string AdditionalInfo { get; set; } } 

    Well, I would like to supplement the previous response with an overload with a constructor accepting the text of the error itself:

     internal class MyException : Exception { public MyException(string message): base(message) { } } 
       public class MyException : Exception { } public class MyClass { public void Execute() { throw new MyException(); } }