-3

Example:

Is it possible to define my own exception type?

Consider i have my own custom method in code behind or BL or DA layer :

public void my_first_method()
{
  // some custom code execution..
  //might throw some errors..
}
//so.. if am not wrong..
//can i have something in my event handler like..

try
{

  my_first_method();
  my_second_method();
  my_third_method();

}
catch(my_first_methodException fex)
{

}
catch(my_second_methodException sex)
{

}
catch(my_third_methodException tex)
{

}
catch(Exception ex)
{
  //if doesn't belongs to above 3 exception come here..
}

I am trying to find out whether this is possible. Please advise. Thanks in advance.

Srinivas
  • 1,063
  • 7
  • 15
  • I would probably rename the variable used to catch and handle the `my_second_methodException` type. Other than that, there's nothing wrong in defining your own exceptions by deriving from the `Exception` class. – Darin Dimitrov Aug 23 '13 at 14:18
  • What have you tried? Search msdn.microsoft.com for custom exception .net http://msdn.microsoft.com/en-us/library/vstudio/ms229064(v=vs.100).aspx – paparazzo Aug 23 '13 at 14:32

2 Answers2

2

Yes; just make a class that inherits Exception, and add appropriate constructors.

For more information, see MSDN.

For example:

[Serializable]
public class NewException : Exception
{
    public NewException() : base("Default message for this type") { }
    public NewException(string message) : base(message) { }
    public NewException(string message, Exception inner) : base(message, inner) { }

    // This constructor is needed for serialization.
   protected NewException(SerializationInfo info, StreamingContext context)
    : base(info, context) { }
}
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • thanks, but how do you call this in your catch block, is it like "throw new NewException(ex.Message,?); what do you pass as a value to the second argument ? – Prathap S V Genny Aug 26 '13 at 06:14
  • @PrathapSVGenny: You should only psss an inner exception if you have one. (If you're adding more information inside a different `catch` block) – SLaks Aug 26 '13 at 13:31
  • @PrathapSVGenny: See http://stackoverflow.com/a/2999314/34397 – SLaks Aug 26 '13 at 13:34
0

It's also worth mentioning that you can create an exception with the visual studio snippet. Just type 'exception' and tab and then name it and add any custom properties etc.

devdigital
  • 34,151
  • 9
  • 98
  • 120