views:

291

answers:

8

I see a lot of code written where an exception is thrown if a parameter is not in the right form, or whatever. Basically "throw new ...".

What is the benefit of this? The exception can be avoided by checking the parameters (Eg if null, write message back to webpage/winform). Why is this approach not used when an exception is expensive?

Thanks

+2  A: 

Throwing an exception:

  • makes it clear to other programmers that the situation is exceptional
  • allows software calling the method involved to clearly handle the problem
  • shows tools and the compiler that the situation is exceptional so that they can assist the programmer
  • allows information to be passed to handling routines in the exception object itself

Printing strings - well - doesn't, really.

In terms of the 'expense' of an exception, exceptions should only be thrown in exceptional circumstances, i.e. rarely and as part of processing errors - I personally have not come across a situation where the 'expense' of an exception is a problem. More discussion on that point in this question.

Brabster
+4  A: 

For example, if you're writing a library to be used by code you don't know about or doesn't exist yet, how that error is handled is down to the code that is making the call.

So throwing an exception is a natural thing to do. Allows you to leave the decision on how to handle that error scenario to the caller/consumer.

AdaTheDev
A: 

Generally and language-agnostically speaking, it is not correct assumption that exceptions are expensive. It depends on many factors.

Generally, exception is a generic way to signal an error condition and it is independent of any form of presentation. Sending out a page with error message would make the error reporting too tightly coupled with presentation, with UI. It is usually not a good idea in terms of flexible and scalable design.

The question is general and language-agnostic, thus the answer does not go deeply into details.

By the way, depending on a programming language, design of error handling, and number of other factors, approaches can be different. However, it's a good idea to learn about various options:

Don't worry too much about the what() message. It's nice to have a message that a programmer stands a chance of figuring out, but you're very unlikely to be able to compose a relevant and user-comprehensible error message at the point an exception is thrown (...)

Given the guidelines above, after a while of consideration, it is not that clear what such error web page should display, what level of information, very technical or more user-friendly. Using exceptions, it gives more flexibility on various levels of the system as one of rules it catch when you need to handle (i.e. display error) ignore otherwise

mloskot
A: 

It is better to throw an exception if the code will be compiled into a library and reused in multiple applications. In that case the client that calls into the library should handle the exceptions appropriately and report a user friendly message.

A: 

There are two main reasons I throw exceptions instead of writing an error message to standard out.

  1. Debugging is easier - I know if the program has exited because of an error. Also, since exceptions in Java can be subclassed, I know exactly what type of error has occurred.

  2. If you write an API, and then decide you want a GUI front-end, perhaps you want to take those exceptions and display them in a message dialog instead of writing them to standard out.

nabs
+10  A: 

A few points are worth making here:

  • First, your supposition that exceptions are expensive is generally untrue - exceptions are, well ... exceptional. They shouldn't be occurring often enough to have any meaningful effect on program performance. And if you are seeing enough exceptions that performance is a problem then you have bigger fish to fry.

  • Second, a well written class, function or module program should be able to detect and handle invalid input somewhat gracefully. It helps the maintainers and debuggers of the code locate the problems as close to their introduction as possible. If arguments are not checked, they can often result in a failure much later in the code - far removed from the actual error. Debugging such problems can be very painful.

  • Third, you assume that all code is aware of the context in which it is executed. A method may be deep in a framework or library and have no knowledge of whether it is running in a web application, console app, NT service, etc. Besides, it'a terrible practice to pepper logic to display information about invalid arguments throughout the body of your code - that responsibility should be centralized and controlled - otherwise you UI could easily become a mess of errors interspersed with actual presentation content.

  • Finally, exceptions allow a program to sometimes handle and recover from a problem rather than exposing it to the user. Don't diminish this capability by directly displaying errors immediately when they occur. Now, granted, most often invalid arguments are a symptom of a programming defect (rather than an environmental or configuration issue) - and so in most cases they can't be handled. But, then again, sometimes they can be handled.

LBushkin
A: 

Exceptions are, in most environments, easier to write tests for than is stuff written to the console:

it "should reject a negative initial balance" do
  Account.new(-1).should raise_error(ArgumentError, "Invalid balance: -1")
end
Wayne Conrad
A: 

This is known as Design by Contract.

The basic idea of Design by Contract is that objects have contracts between them, and if a caller does not fulfill the contract the receiver should fail with an exception rather than trying to guess the callers intention. At the end of the day, this leads to more stable software (in particular when more than one person is writing on project, since then the contract also become contracts between programmers).

 

PS: An important issue of Design by Contract that is often forgotten is the following. It must be possible for the client to know whether it fulfills the contract or not. So eg, if the contract of a stack is that client may only pop when the stack is not empty there must be an isEmpty method to check that and clients should use that method before calling pop. So this is why code that uses Design by Contract is cluttered with exceptions that are nevertheless never thrown.

Adrian