Reputation: 2729
I am trying to have my page call a method and, if it fails, display an error in my mbResult control. However, since my method is a void method, I am having a hard time throwing the exception. If I throw it from the method end it will not display in my error box.
I have the following code in my my page:
try
{
Facade.AcceptChanges();
}
catch(FarAlreadyExistsException)
{
mbResult.Message = new MessageInfo(FutureActivitiesAlreadyExistsMessage);
return;
}
the accept changes method is this
public void AcceptChanges()
{
try
{
DataContext.SaveChanges();
}
catch (Exception)
{
return;
}
}
Upvotes: 0
Views: 569
Reputation: 2290
public void AcceptChanges() {
try
{
DataContext.SaveChanges();
}
catch (Exception cause) {
throw new FarAlreadyExistsException(cause);
}
}
You don't throw the exception, so you aren't going to catch it in the try-catch of the first method
Upvotes: 3
Reputation: 15803
Remove the second try-catch to let the exception get caught in your first catch block:
public void AcceptChanges()
{
DataContext.SaveChanges();
}
EDIT: It seems you should also apply the following change:
try
{
Facade.AcceptChanges();
}
catch(Exception) // according to the documentation, this should be an OptimisticConcurrencyException
{
mbResult.Message = new MessageInfo(FutureActivitiesAlreadyExistsMessage);
return;
}
Upvotes: 3
Reputation: 2488
You shouldn't catch the exception in AcceptChanges()
then and let first try-catch block handle it.
Upvotes: 1
Reputation: 13335
You are swallowing the exception in AcceptChanges
. Remove the Try;Catch;
in AcceptChanges
and let it bubble up.
Upvotes: 1
Reputation: 8623
Don't have the generic try-catch
statement inside the AcceptChanges()
method. Let the Exception
that occurs inside DataContext.SaveChanges()
bubble up to your try-catch
inside the first section of code.
You should only handle exceptions that you are expecting (unless you really don't care if a piece of code fails). And you should only handle exceptions in the exact places that care about the exception.
Upvotes: 1
Reputation: 32438
You shouldn't handle the exception in AcceptChanges
if you're not going to do anything. It's just swallowing the error, so your outer try...catch
block won't see it (and the code in the catch
block won't get triggered.
Remove the try...catch
within your AcceptChanges
method then the catch code in the method that calls it will catch the exception (as long as it's of the correct type.
Upvotes: 2