views:

94

answers:

4

Suppose I create a some client code consisting of a couple of classes. A user is able to create a class/object that causes an exception to be thrown. Is this bad design? Should your ideal code be such that it is impossible for someone to cause an exception?

+2  A: 

No, design patterns do not discount exceptions. There may be portions/functions within your library where a strong/weak exception guarantee is desirable. But that depends entirely on the library.

dirkgently
+1  A: 

No, every API that I have used is perfectly capable of throwing exceptions. Look at it this way; you pass in some "bad" data to a framework class. What would you rather have happen; an exception is thrown which makes the problem immediately obvious, or the call fails silently and you spend hours trying to figure out why your code is not working?

Ed Swangren
+1  A: 

There are countless examples of APIs that throw exceptions when given an object supplied by the user. This is by no means bad design by good design and indicates the API is validating its input.

The first example I thought of was .NET's System.IO.File.Delete(string) function which will throw an exception if the file to be deleted is not found.

Brian Ensink
A: 

Your classes can throw exceptions, but you should check all the input to it and throw controlled exceptions when possible. I mean, if you know some argument is invalid, throw an InvalidArgumentException or something like it. Catch the errors you should, treat them or throw them.

Morgaelyn