views:

211

answers:

4

Hi all, 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 advanced.

Juan Zamudio

A: 

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

Mladen Prajdic
Yeah that's true, but what about an IOException, I can catch that but what do I do with it, do I notify about the error with a MessageBox or a"Yellow Bar" a la IE. or just silently handle it.
Juan Zamudio
+2  A: 

Hi, 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

tamberg
that looks interesting, i will take a look, thanks.
Juan Zamudio
A good introduction is http://se.ethz.ch/~meyer/publications/computer/contract.pdf
tamberg
A: 

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.

Mark Cidade
A: 

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

Frank V