Juan Zamudio
Juan Zamudio

Reputation: 479

Correct way to Handle Exceptions in UserControl

I'm build an UserControl and I'm not sure how to handle exceptions, the Control itself is not very complicated, the User chose an image from disk so they can authorize it, I don't know exactly how the control will be used so if I use a MessageBox I might block the application, and if I just re-throw it I might crash it.

thanks in advance.

Juan Zamudio

Upvotes: 2

Views: 1474

Answers (4)

tamberg
tamberg

Reputation: 2017

this is a common problem facing developers who build libraries. Try to weed out bugs and decide for the remaining error cases if it's an expected error (your control should not throw an exception but rather gracefully handle the error) or an unexpected exceptional condition (your control must throw an exception as soon as possible).

You might also have a look at Design By Contract, a methodology to declare required preconditions and guaranteed postconditions. This may sound academic, but it leads to more robust code.

UPDATE: A good introduction is http://se.ethz.ch/~meyer/publications/computer/contract.pdf

Regards, tamberg

Upvotes: 3

Frank V
Frank V

Reputation: 25419

In addition to what's been said, I also want to mention that you should try to have your control avoid exceptions by checking for different object states and "preventing" rather then allowing an exception to be raised.

Keep mind mind that throwing an exception is a rather expensive process and (as I've been told in the past) exceptions should be reserved for truly "exceptional" unexpected cases...

Best Regards,
Frank

Upvotes: 0

Mark Cidade
Mark Cidade

Reputation: 99957

Only handle exceptions that you know of and know what to do with. Don't bother with generic handlers, like a MessageBox. Just let it propogate to the application where there's more context for diagnosing the error. It's their responsibility to catch any exceptions so that the application doesn't crash. In the case of an exception they can't do anything about because it has to do with the control's internals, you should handle that yourself and if it's partially the user's fault, wrap the exception with a message saying what is missing, with the original exception available via the InnerException property.

Upvotes: 0

Mladen Prajdic
Mladen Prajdic

Reputation: 15677

unhandled exceptions should definitely be thrown so that the people using your control can see what's wrong.

Upvotes: 0

Related Questions