CiccioMiami
CiccioMiami

Reputation: 8266

Code does not catch FormatException in C#

I have the following method in the class ProductServices:

public bool IsDownloadAllowed(int Id, string productId)
{
  if (CustomStringFunctions.IsGuid(productId))
  {
     //Do Something
  }
  else
  {
     throw new FormatException("The Guid must be a valid Guid!");
  }
}

If I use the method in the following set of instructions:

var _productServices = new ProductServices();
try
{
   var flag = _productServices.IsDownloadAllowed(Id, productId);
   //do something
}

catch (Exception e)
{
   //handle exception
}

The exception is not caught by the catch statement. I also tried to replace Exception with FormatException with no luck. What am I doing wrong?

Upvotes: 2

Views: 1251

Answers (2)

phoog
phoog

Reputation: 43056

Your code looks correct. A possible explanation for your problem is that CustomStringFunctions.IsGuid is incorrectly returning true, so the \\do something branch is executing instead of the exception-throwing branch.

Upvotes: 1

Aghilas Yakoub
Aghilas Yakoub

Reputation: 28990

You must have mute exception in this code

if (CustomStringFunctions.IsGuid(productId))
  {
     //Do Something
  }

You must be sure that you throw exception when occured (In the Do Something)

Sample of mute exception

Try
{

}
Catch(Exception ex)
{
   //throw don't exist
}

Upvotes: 1

Related Questions