Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Should methods return nulls or throw exceptions 3

Status
Not open for further replies.

AndrewJMarshall

Programmer
Jun 8, 1999
24
0
0
US
I know it seems like a goofy question, but ...

I'm writing a data layer class that provides methods to retrieve objects from a database by their ID. If no record exists for a specific ID, should the methods provided return null or throw an exception?

Please provide your reasoning as this is a mostly academic question. My suspicion is the that the "right" answer is "it depends". 8-(

Thanks,
Andrew
 
I had totally forgotten about this conversation until I came accross an interesting best-practice in the vs.net 2005 help files:

Do not rely on exceptions in your code Exceptions can cause performance to suffer significantly, so you should avoid using them as a way to control normal program flow. If it is possible to detect in code a condition that would cause an exception, do so rather than catching the exception itself and handling the condition. Common scenarios to detect in code include checking for null, assigning a value to a String that will be parsed into a numeric value, or checking for specific values before applying math operations. The following example demonstrates code that could cause an exception and code that tests for a condition. Both produce the same result.

Code:
' This is not recommended.
Try
   result = 100 / num
Catch (e As Exception)
  result = 0
End Try

' This is preferred.
If Not (num = 0)
   result = 100 / num
Else
  result = 0
End If

Just wanted to share.

D
 
That is true, but it is also pretty obvious. The only time you'd want to allow an exception in a case like that is if other logic in your program is expected to set the num value to non-zero. By checking for non-zero in that code, you would be duplicating logic. Of course, the exception should not be caught immediately (if your code did requre that the exception not propagate out of that function, then checking for non-zero would again be more appropriate). Instead, the exception should be allowed to propagate up higher to some point where serious logic errors are handled.
 
Mhm.
Joining the thread late, I like to tell you my thoughts and observations.

The result=100/0 and the display(rows) - examples both don't return values or throw exceptions, so they don't fit to the topic discussed.

I see strong arguments on bobs side, because newbies will not expect errors to happen, but an experienced developer will.
Expectation is very relativ, and if you are an experienced developer, you may anticipate a lot of errors.

But sometimes that's not of too much help.
A sql-connection may terminate quiete after testing for it.

Considering something an error or not depends on the context. Sometimes zero rows are a reasonable result, and sometimes it is an error.

If you can heal an error, you should do.
Just in case you don't know, how to react to an error, you should let the calling context decide, what to do.

Now, what's about returning an error-code?
A method 'char readChar ()' might return any char, and there is no possibility, to return an errorcode.
Some libraries return an bigger datatyp, just to make an special errorcode possible.
If the caller needs characters, he has to cast/ convert every regular result, just to make the seldom 'end-of-file=-1' possible.

Depending on the situation, you might know before, how many chars you read, or you may have to read until reaching EOF, and you might only know, that EOF was reached, by trying to read further.

Another problem with returning error-codes is, that the caller isn't evaluating the returned value:
Code:
c = readChar ();
// skip two Chars:
readChar ();  // ooops! eof!
readChar ();
d = readChar ();

C-Libraries did return errorcodes often, and programmers often ignored return-values. That's been a reason for c++ to use exceptions instead.

Sometimes 'null' might be a value, which can only mean 'Error'. But which?
Often there are differnt error-causes possible, like 'FileNotFound' or 'PermissionDenied' or 'UnexpectedEOF'.

Performance-considerations have some problems too:
a) They might depend on the Language.
I don't know for VB, but in Java, entering a 'try'-Block is for free. Only if an Exception is caught, time is spend in creating and throwing it.
b) Performance might depend on your version of the language.
c) premature optimization is the root of all evil
d) alternative approaches aren't for free.
For example:
If you use 'int i = Integer.parseInt (stringNumber);', you could parse the String before, to ensure, it is a well formed Integer.
Well - that's exactly what parseInt (s) is doing, while trying to generate an int from the String. There isn't much you may do, having performance in mind.

Conclusion/ Rules of thumb:
If you may avoid an error, do it.
If returning nothing isn't an error, don't throw an exception, but null, a Null-Object, an empty array or an empty List.
If can heal an error in place, catch the exception yourself, and don't propagate it.
If you don't know how to react to an error, throw an exception.

Depending on your context, your language and your experience, thinking can't be replaced by rules of thumb.

seeking a job as java-programmer in Berlin:
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top