I am trying to understand how to use a custom exception in the right way.
I have used try/catch many times but never understod when to use your own class off exceptions. I have read and watch some off the many tutorials out there, but I can't get my head around this.
This is my CustomException
class:
[Serializable]
class CustomException : FormatException
{
/// <summary>
/// Just create the exception
/// </summary>
public CustomException()
: base() {
}
/// <summary>
/// Create the exception with description
/// </summary>
/// <param name="message">Exception description</param>
public CustomException(String message)
: base(message) {
}
/// <summary>
/// Create the exception with description and inner cause
/// </summary>
/// <param name="message">Exception description</param>
/// <param name="innerException">Exception inner cause</param>
public CustomException(String message, Exception innerException)
{
}
}
This is where I try to use it:
/// <summary>
/// Checks if parse works
/// </summary>
/// <returns></returns>
public static int ParseInput(string inInt)
{
try
{
int input = int.Parse(inInt);
return input;
}
catch (CustomException)
{
throw new CustomException();
}
catch (Exception ex)
{
MessageBox.Show("Use only numbers! " + ex.Message);
return -1;
}
}
Now what do I do wrong? Becuse the program crash att this line int input = int.Parse(inInt);
, it never comes to my custom exception? If I do use the classic Exception
class it all works.