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.
In your code you are only throwing your type of exception when you caught it before, which will never happen, as the system will not throw it.
Normally you would do something like this.
try
{
// do something
if (some condition)
throw new MyCustomException() ;
}
catch (SomeOtherException e)
{
// Handle other exceptions
}
In your case, the system will throw a FormatException
, but not your own exception class, as it doesn't know about it. As your exception class is more specific as the FormatException
, the catch block will not be called. However, it should work like this:
public static int ParseInput(string inInt)
{
try
{
int input = int.Parse(inInt);
return input;
}
catch (FormatException e)
{
throw new CustomException("Format error!", e);
}
catch (Exception ex)
{
MessageBox.Show("Use only numbers! " + ex.Message);
return -1;
}
}
In addition, your code has one flaw: When any Exception
is caught, a message will be displayed to the user and -1 will be the return value (is -1 not a valid input...?). When a FormatException
is caught, error handling is left to the called by re-throwing the exception - why?
Please remember that exceptions don't "fall through":
try
{
}
catch (FormatException e1)
{
// This will throw an exception, but it will **not** be caught here,
// but control goes back to the caller
throw new Exception();
}
catch (Exception e2)
{
// This block will not get called when an exception occurs in
// above handler. It will only get called when an exception other
// than FormatException occurs.
}