-3

Let's say I have the following function:

unsigned char *f(unsigned char*, int, int, long, const char*);

I could change the return value to HRESULT (or my own defined), but I have to change the entire code inside a function. Or I could simly use throw to point out the error.

My questions are:

  • What advantages/disadvantages are of returning HRESULT?
  • What advantages/disadvantages are with throw?
  • And which one is the more safer way?

Should I use the second one or it completly depends on what I prefer?

EDIT: I didn't strictly mean using HRESULT. You can define your own enum for error-handling to be independent of Windows

Quest
  • 2,764
  • 1
  • 22
  • 44
  • If you should change to `HRESULT` or not depends very much on how the function currently is used, and also what it's doing. Changing to use `HRESULT` also ties you down to a single platform (Windows). How to handle errors is a very broad subject, and also subject to lot of opinions. – Some programmer dude Dec 15 '14 at 10:32
  • [This is the first link in Google on 'throw exception vs return error code' request](http://stackoverflow.com/questions/253314/exceptions-or-error-codes). – FreeNickname Dec 15 '14 at 10:33
  • @JoachimPileborg I didn't strictly mean `HRESULT`.. you could of course create a new enum for error handling for example – Quest Dec 15 '14 at 10:34
  • Please see my explanation below... – ravi Dec 15 '14 at 10:52

2 Answers2

2

I would say you should always resort to exceptions when dealing with errors in C++. Let's see why is it better alternative in your case.

First HRESULT is a data type used in Windows operating systems, which instantly make your code non-portable on linux platform.

Second, first covers all other aspects.

Why exceptions are better than error-codes?

1) Exceptions separate erroneous flow from normal flow which is hard to get with error codes.

2) Sometimes there's no reasonable error-code you could send to the caller.

3) There's a more responsibility for checking whether normal/erroneous exit happened on usability department if you use error codes. However, uncaught exception would bring your program to dead halt.

These are just few benefits of using exceptions over error codes.

ravi
  • 10,994
  • 1
  • 18
  • 36
  • With your own defined error list #2 is no more a problem but +1 ;) – Quest Dec 15 '14 at 10:56
  • When choosing to go with exceptions you need to take a bit more care with making your code exception safe, so you don't start leaking resources or getting into invalid states when an exception is thrown. – Lionel Dec 15 '14 at 11:18
1

I would say it completly depends on what you prefer. There is no advantage or disadvantage over another(with your edit). I, for example, prefer using throw because the end user is forced to do some kind of error-checking, so I use throw almost in every situation.