Catching Exception, do's and dont's - exception

Is it always a bad programming technique to leave a catch block empty when using a try-catch block?
In cases where I am expecting an exception, for example, I am reading 10 values from a file...and converting each value into a String. There is a possibility that one of the 10 values can be a null, but I don't want to stop my execution at that point and rather continue (obvious use of try catch)
A lame example of what I am trying:
String _text = textReader.ReadLine(); //Assuming this RETURNS a NULL value
try {
String _check = _text.ToString();
//Do something with _check, but it should not be NULL
}
catch (Exception)
{ //Do Nothing }
At this point, when I catch an exception:
1. I don't want to log this. Since I am expecting a buggy value.
2. I don't want to re-throw the exception up the call-stack.
3. I want to simply continue with my execution
Under these cases, is it acceptable to leave the catch empty? Or is this a complete NO-NO and there is a better way to handle this?
I presume this can be a community wiki since it also deals with programming techniques.
- Ivar

I assume that you mean
_text.ToString()
and you're concerned about the case when _text may be null?
I don't like your use of exceptions in this case. Put yourself in the mind of someone needing to maintain this code. They see:
catch (Exception) { }
Can they really deduce that all this is doing is catching the Null case? They have to consider what other Exceptions might be thrown. At the very least this raises uncertainty in the maintainer's mind.
Why could you not code:
if ( _text != null ) {
String _check = _nullValue.ToString();
}
This says exactly what you mean.
But taking this further, what does getting a value of NULL mean? You're reading a file that may have 10 values in it. I'm guessing that maybe blank line gives a null for you?
What do intend if you get:
1
2
<blank line>
4
...
10
So that's 9 good values and a blank line. What will you do if instead you get 10 good values and a blank line? 11 good values? 11 good values and a blank line?
My point is that silently ignoring oddities in user input is often a bad idea. It's quite likely that some of the cases above are actually typos. By warning in some of these cases you may be very helpful to the user. This implies that probably most odditities in input need at least some kind of count, if not an actual immediate error log.
You might, for example, emit a message at the end
Your file contained 13 lines, two lines were blank. We processed 10 valid values and ignored one.
At the very leasyt for debugging purposes you might have trace statements in the error paths.
Summary: completely ignoring Exceptions is rarely the right thing to do.

If it's expected it's not really exceptional. Is this a good use of exceptions? It may be more appropriate to test for a null value before trying to do stuff.
if(_text != null)
// do something

The best argument I liked was that the code will become highly un-maintainable. And my aim was to make my code as easy to understand as possible.
With the suggestions above, I have an army of ternary operators in place (my personal favorite over big if-else blocks).
And the code definitely looks better! and I think unless the try-catch is well documented, I don't myself see a good reason for having empty catch statements anymore.
Thanks Guys!!
-Ivar

Related

Actually CATCHing exceptions without creating GOTO

Looking over my Raku code, I've realized that I pretty much never use CATCH blocks to actually catch/handle error. Instead, I handle errors with try blocks and testing for undefined values; the only thing I use CATCH blocks for is to log errors differently. I don't seem to be alone in this habit – looking at the CATCH blocks in the Raku docs, pretty much none of them handle the error in any sense beyond printing a message. (The same is true of most of the CATCH blocks in Rakudo.).
Nevertheless, I'd like to better understand how to use CATCH blocks. Let me work through a few example functions, all of which are based on the following basic idea:
sub might-die($n) { $n %% 2 ?? 'lives' !! die 418 }
Now, as I've said, I'd normally use this function with something like
say try { might-die(3) } // 'default';
But I'd like to avoid that here and use CATCH blocks inside the function. My first instinct is to write
sub might-die1($n) {
$n %% 2 ?? 'lives' !! die 418
CATCH { default { 'default' }}
}
But this not only doesn't work, it also (very helpfully!) doesn't even compile. Apparently, the CATCH block is not removed from the control flow (as I would have thought). Thus, that block, rather than the ternary expression, is the last statement in the function. Ok, fair enough. How about this:
sub might-die2($n) {
ln1: CATCH { default { 'default' }}
ln2: $n %% 2 ?? 'lives' !! die 418
}
(those line numbers are Lables. Yes, it's valid Raku and, yes, they're useless here. But SO doesn't give line numbers, and I wanted some.)
This at least compiles, but it doesn't do what I mean.
say might-die2(3); # OUTPUT: «Nil»
To DWIM, I can change this to
sub might-die3($n) {
ln1: CATCH { default { return 'default' }}
ln2: $n %% 2 ?? 'lives' !! die 418
}
say might-die3(3); # OUTPUT: «'default'»
What these two reveal is that the result of the CATCH block is not, as I'd hopped, being inserted into control flow where the exception occurred. Instead, the exception is causing control flow to jump to the CATCH block for the enclosing scope. It's as though we'd written (in an alternate universe where Raku has a GOTO operator [EDIT: or maybe not that alternate of a universe, since we apparently have a NYI goto method. Learn something new every day…]
sub might-die4($n) {
ln0: GOTO ln2;
ln1: return 'default';
ln2: $n %% 2 ?? 'lives' !! GOTO ln1;
}
I realize that some critics of exceptions say that they can reduce to GOTO statements, but this seems to be carrying things a bit far.
I could (mostly) avoid emulating GOTO with the .resume method, but I can't do it the way I'd like to. Specifically, I can't write:
sub might-die5($n) {
ln1: CATCH { default { .resume('default') }}
ln2: $n %% 2 ?? 'lives' !! die 418
}
Because .resume doesn't take an argument. I can write
sub might-die6($n) {
ln1: CATCH { default { .resume }}
ln2: $n %% 2 ?? 'lives' !! do { die 418; 'default' }
}
say might-die6 3; # OUTPUT: «'default'»
This works, at least in this particular example. But I can't help feeling that it's more of a hack than an actual solution and that it wouldn't generalize well. Indeed, I can't help feeling that I'm missing some larger insight behind error handling in Raku that would make all of this fit together better. (Maybe because I've spent too much time programming in languages that handle errors without exceptions?) I would appreciate any insight into how to write the above code in idiomatic Raku. Is one of the approaches above basically correct? Is there a different approach I haven't considered? And is there a larger insight about error handling that I'm missing in all of this?
"Larger insight about error handling"
Is one of the approaches [in my question] basically correct?
Yes. In the general case, use features like try and if, not CATCH.
Is there a different approach I haven't considered?
Here's a brand new one: catch. I invented the first version of it a few weeks ago, and now your question has prompted me to reimagine it. I'm pretty happy with how it's now settled; I'd appreciate readers' feedback about it.
is there a larger insight about error handling that I'm missing in all of this?
I'll discuss some of my thoughts at the end of this answer.
But let's now go through your points in the order you wrote them.
KISS
I pretty much never use CATCH blocks to actually catch/handle error.
Me neither.
Instead, I handle errors with try blocks and testing for undefined values
That's more like it.
Logging errors with a catchall CATCH
the only thing I use CATCH blocks for is to log errors differently.
Right. A judiciously located catchall. This is a use case for which I'd say CATCH is a good fit.
The doc
looking at the CATCH blocks in the Raku docs, pretty much none of them handle the error in any sense beyond printing a message.
If the doc is misleading about:
The limits of the capabilities and applicability of CATCH / CONTROL blocks; and/or
The alternatives; and/or
What's idiomatic (which imo is not use of CATCH for code where try is more appropriate (and now my new catch function too?)).
then that would be unfortunate.
CATCH blocks in the Rakudo compiler source
(The same is true of most of the CATCH blocks in Rakudo.).
At a guess those will be judiciously placed catchalls. Placing one just before the callstack runs out, to specify default exception handling (as either a warning plus .resume, or a die or similar), seems reasonable to me. Is that what they all are?
Why are phasers statements?
sub might-die1($n) {
$n %% 2 ?? 'lives' !! die 418
CATCH { default { 'default' }}
}
this not only doesn't work, it also (very helpfully!) doesn't even compile.
.oO ( Well that's because you forgot a semi-colon at the end of the first statement )
(I would have thought ... the CATCH block [would have been] removed from the control flow)
Join the club. Others have expressed related sentiments in filed bugs, and SO Q's and A's. I used to think the current situation was wrong in the same way you express. I think I could now easily be persuaded by either side of the argument -- but jnthn's view would be decisive for me.
Quoting the doc:
A phaser block is just a trait of the closure containing it, and is automatically called at the appropriate moment.
That suggests that a phaser is not a statement, at least not in an ordinary sense and would, one might presume, be removed from ordinary control flow.
But returning to the doc:
Phasers [may] have a runtime value, and if evaluated [in a] surrounding expression, they simply save their result for use in the expression ... when the rest of the expression is evaluated.
That suggests that they can have a value in an ordinary control flow sense.
Perhaps the rationale for not removing phasers from holding their place in ordinary control flow, and instead evaluating to Nil if they don't otherwise return a value, is something like:
Phasers like INIT do return values. The compiler could insist that one assigns their result to a variable and then explicitly returns that variable. But that would be very un Raku-ish.
Raku philosophy is that, in general, the dev tells the compiler what to do or not do, not the other way around. A phaser is a statement. If you put a statement at the end, then you want it to be the value returned by its enclosing block. (Even if it's Nil.)
Still, overall, I'm with you in the following sense:
It seems natural to think that ordinary control flow does not include phasers that do not return a value. Why should it?
It seems IWBNI the compiler at least warned if it saw a non-value-returning phaser used as the last statement of a block that contains other value-returning statements.
Why don't CATCH blocks return/inject a value?
Ok, fair enough. How about this:
sub might-die2($n) {
ln1: CATCH { default { 'default' }}
ln2: $n %% 2 ?? 'lives' !! die 418
}
say might-die2(3); # OUTPUT: «Nil»
As discussed above, many phasers, including the exception handling ones, are statements that do not return values.
I think one could reasonably have expected that:
CATCH phasers would return a value. But they don't. I vaguely recall jnthn already explaining why here on SO; I'll leave hunting that down as an exercise for readers. Or, conversely:
The compiler would warn that a phaser that did not return a value was placed somewhere a returned value was probably intended.
It's as though we'd written ... a GOTO operator
Raku(do) isn't just doing an unstructured jump.
(Otherwise .resume wouldn't work.)
this seems to be carrying things a bit far
I agree, you are carrying things a bit too far. :P
.resume
Resumable exceptions certainly aren't something I've found myself reaching for in Raku. I don't think I've used them in "userspace" code at all yet.
(from jnthn's answer to When would I want to resume a Raku exception?.)
.resume doesn't take an argument
Right. It just resumes execution at the statement after the one that led to an exception being thrown. .resume does not alter the result of the failed statement.
Even if a CATCH block tries to intervene, it won't be able to do so in a simple, self-contained fashion, by setting the value of a variable whose assignment has thrown an exception, and then .resumeing. cf Should this Raku CATCH block be able to change variables in the lexical scope?.
(I tried several CATCH related approaches before concluding that just using try was the way to go for the body of the catch function I linked at the start. If you haven't already looked at the catch code, I recommend you do.)
Further tidbits about CATCH blocks
They're a bit fraught for a couple reasons. One is what seems to be deliberate limits of their intended capability and applicability. Another is bugs. Consider, for example:
My answer to SO CATCH and throw in custom exception
Rakudo issue: Missing return value from do when calling .resume and CATCH is the last statement in a block
Rakudo issue: return-ing out of a block and LEAVE phaser (“identity”‽)
Larger insight about error handling
is there a larger insight about error handling that I'm missing in all of this?
Perhaps. I think you already know most of it well, but:
KISS #1 You've handled errors without exceptions in other PLs. It worked. You've done it in Raku. It works. Use exceptions only when you need or want to use them. For most code, you won't.
KISS #2 Ignoring some native type use cases, almost all results can be expressed as valid or not valid, without leading to the semi-predicate problem, using simple combinations of the following Raku Truth value that provide ergonomic ways to discern between non-error values and errors:
Conditionals: if, while, try, //, et al
Predicates: .so, .defined, .DEFINITE, et al
Values/types: Nil, Failures, zero length composite data structures, :D vs :U type constraints, et al
Sticking with error exceptions, some points I think worth considering:
One of the use cases for Raku error exceptions is to cover the same ground as exceptions in, say, Haskell. These are scenarios in which handling them as values isn't the right solution (or, in Raku, might not be).
Other PLs support exceptions. One of Raku's superpowers is being able to interoperate with all other PLs. Ergo it supports exceptions if for no other reason than to enable correct interoperation.
Raku includes the notion of a Failure, a delayed exception. The idea is you can get the best of both worlds. Handled with due care, a Failure is just an error value. Handled carelessly, it blows up like a regular exception.
More generally, all of Raku's features are designed to work together to provide convenient but high quality error handling that supports all of the following coding scenarios:
Fast coding. Prototyping, exploratory code, one-offs, etc.
Control of robustness. Gradually narrowing or broadening error handling.
Diverse options. What errors should be signalled? When? By which code? What if consuming code wants to signal that producing code should be more strict? Or more relaxed? What if it's the other way around -- producing code wants to signal that consuming code should be more careful or can relax? What can be done if producing and consuming code have conflicting philosophies? What if producing code cannot be altered (eg it's a library, or written in another language)?
Interoperation between languages / codebases. The only way that can work well is if Raku provides both high levels of control and diverse options.
Convenient refactoring between these scenarios.
All of these factors, and more, underlie Raku's approach to error handling.
CATCH is a really old feature of the language.
It used to only exist inside of a try block.
(Which is not very Rakuish.)
It is also a very rarely used part of Raku.
Which means that not a lot of people have come up with “pain points” of the feature.
So then very rarely has anyone done any work to make it more Rakuish.
Both of those combined make it so that CATCH is a rather featureless part of the language.
If you look at the test file for the feature, you will note that most of it was written in 2009 when the test suite was still a part of the Pugs project.
(And most of the rest are tests for bugs that have been found over the years.)
There is a very good reason that few people have tried to add new behaviours to CATCH, there are plenty of other features that are much nicer to work with.
If you want to replace a result in the event of an exception
sub may-die () {
if Bool.pick {
return 'normal'
} else {
die
}
}
my $result;
{
CATCH { default { $result = 'replacement' }}
$result = may-die();
}
It is much easier to just use try without CATCH, along with defined‑or // to get something that works very similarly.
my $result = try { may-die } // 'replacement';
It is even easier if you are dealing with soft failures instead of hard exceptions, because you can just use defined‑or by itself.
sub may-fail () {
if Bool.pick {
return 'normal'
} else {
fail
}
}
my $result = may-fail() // 'replacement';
In fact the only way to use CATCH with a soft failure is to combine it with try
my $result;
try {
CATCH { default { $result = 'replacement' }}
$result = may-fail();
}
If your soft failure is the base of all failure objects Nil, you can either use // or is default
my $result = may-return-nil // 'replacement';
my $result is default<replacement> = may-return-nil;
But Nil won't just work with CATCH no matter how much you try.
Really the only time I would normally use CATCH is when I want to handle several different errors in different ways.
{
CATCH {
when X::Something { … }
when X::This { … }
when X::That { … }
default { … }
}
# some code that may throw X::This
…
# some code that may throw X::NotSpecified (default)
…
# some code that may throw X::Something
…
# some code that may throw X::This or X::That
…
# some code that may fail instead of throw
# (sunk so that it will throw immediately)
sink may-fail;
}
Or if I wanted to show how you could write this [terrible] Visual Basic line
On Error Resume Next
In Raku
CATCH { default { .resume } }
That of course doesn't really answer your question in the slightest.
You say that you expected CATCH to be removed from the control flow.
The whole point of CATCH is to insert itself into the exceptional control flow.
Actually that's not accurate. It doesn't so much insert itself into the control flow as ending the control flow while doing some processing before moving on to the caller/outside block. Presumably because the data of the current block is in an erroneous state and should no longer be trusted.
That still doesn't explain why your code fails to compile.
You expected CATCH to have its own special syntax rule when it comes to the semicolon ending a statement.
If it worked the way you expected it would fail one of the important [syntax] rules in Raku, “there should be as few special cases as possible”. Its syntax is not special in any way unlike what you seem to expect.
CATCH is just one of many phasers with one important extra bit of functionality, it stops exception propagation down the call stack.
What you seem to be asking for it to instead alter the result of an expression that may throw.
That doesn't seem like a good idea.
$a + may-die() + $b
You want to be able to replace the exception from may-die with a value.
$a + 42 + $b
Basically you are asking for the ability to add action‑at‑a‑distance as a feature.
There is also a problem, what if you actually wanted $a + may‑die to be replaced instead.
42 + $b
There is no way in your idea for you to specify that.
Even worse, there is a way that could accidently happen. What if may‑die started returning a failure instead of exception. Then it would only cause an exception when you tried to use it, for example by adding it to $a.
If some code throws an exception, the block is in an unrecoverable state and it needs to halt execution. This far, no farther.
If an expression throws an exception, the result of executing the statement it is in, is suspect.
Other statements may rely on that broken statement, so then the whole block is also suspect.
I do not think it would be that good of an idea if it instead allowed the code to continue but with a different result for the current expression. Especially if that value can be far removed from the expression somewhere else inside of the block. (action‑at‑a‑distance)
If you could come up with some code that would be vastly improved with .resume(value), then maybe it could be added.
(I personally think that leave(value) would be more useful in such a circumstance.)
I will grant that .resume(value) seems like it may be useful for control exceptions.
(Caught with CONTROL instead of CATCH.)

too greedy condition, or misused exception?

I have two alternative code fragments, with an intention to do (approximately) the same:
Closed-ended condition, with 3 cases of inputs resulting into just 2 cases of outputs:
this.showDropdowns ? parseInt(this.uploadForm.get('location').value, 10) : null;
Open-ended conditioning, with 3 possible cases of inputs resulting into 3 recombined (table non-plain matching) cases of outputs:
try {parseInt(this.uploadForm.get('location').value, 10)} catch (ParseIntError e) {return null;}
The first case is strict, allowing only the two resulting options explicitly prepared by the programmer: Either gives null (i), or the parsed value (ii), or the parsing falls (iii) back to the null.
See the Closed/Open questions described on Wikipedia, to understand me what I mean.
The second code-fragment is not so greedy, does not swallow any possible exception, so the values are the two (three) expected by a programmer: The successfully parsed value (a), or there is still an allowed option for any unexpected result, as an explicitly caught Exception (also merging the null input/output case (b) with the parsing error exception (c), the non-null input, to be parsed, but unprocessable), but still yet allowing a fourth case of whatever completely unimaginable in the moment of the programming (d), still letting it to bubble up as an uncaught exception.
The inputs could be just two, in general: null, or an Object.
The outputs on the other hand could be more complicated:
the hardcoded null, after the IF;
the successfully parsed value;
or Exceptions:
Completely wrong Object-type for the particular parsing.
Parsable Object-type, but wrong values in it, in many ways...
So the questions:
Is the first one too naive and too greedy, swallowing too much, or oppositely the aggregation/swallowing is the recommended way?
Would the second be misusing of the mechanism of exceptions, or just the standard plain usage?
Are these known distinguished cases/options, how to resolve problems? These might be even so general, that there are some rules, philosophical how-to's or Good practices, to judge/recognize, when exactly to use the 1st, or the 2nd? So what are the rules, the recommendations? Thanks.

Is this a valid reason for an empty try catch or is there a more elegant solution?

Assume I have the following class hierarchy:
A Person object contains a Customer object and the Customer object contains an Address object.
I do not care if the customer has an address or not, but if they do, I want to save it to the database. So in this case, is it perfectly fine to have something like:
try
{
Address addr = person.Customer.Address;
db.SaveAddress(addr);
}
catch
{
//I don't care, but if it is there, just save it.
}
In the above, I don't care if Customer is null or Address is null. The other alternative I had was
if(person.Customer != null)
{
if(person.Customer.Address != null)
{
}
}
The above can long though if the hierarchy is long. Is there a more elegant way to check if a chain of objects is null without having to check each one.
You should always use exceptions for exceptional cases. You will suffer through performance penalties as there will be some context switching on the CPU.
You could combine the 2nd example to 1 line with most short circuiting languages.
if(person.Customer != null && person.Customer.Address != null)
{
}
Example:
bool isAddressValid = person.Customer != null && person.Customer.Address != null;
if (isAddressIsValid) { }
Context Switching: http://en.wikipedia.org/wiki/Context_switch
There are several reasons to have your code check the condition, instead of just catching any exception and ignoring it. The first two that come to mind are:
Like other people mentioned, using exceptions has a very high performance cost (when exception are actually thrown). For a valid and common scenario, you would usually prefer to get an indication of an error through some condition or method return value.
Even if you do detect a possible condition by catching an exception, it is recommended to throw a specific exception type, and only catch the type of exception you allow. Because what if something else went wrong and a different exception was thrown? (for example what if Save through an OutOfMemoryException? You would have caught and ignored it). In your case, even if you went for catching and ignoring an exception, it would be better to only catch NullReferenceException, and ignore the rest. Even better would have been define your own exception type (e.g. CustomerHasNoAddressException) and only catch that.
You should always check for null (or whatever condition) if you know it may occur and you can avoid the exception, the reason for this being that exceptions are slow, and as you point out, inelegant. Just use:
if(person.Customer != null && person.Customer.Address != null) {
// ...
}
That is a very bad use of an Exception. There are sometimes "questionable" and "sneaky" places, but that is just downright ... bad.
It is bad because you are covering up every possible exception inside there, and adding no self-documentation to the code as to what may be covered up.
What if SavePerson could not save the person? :( Everything would happily continue (well, except for Mr. Fred who isn't saved... he might be upset.)
The code with the explicit "null-check" isn't plagued with this issue, and it adds self-documentation. It is evident that a null case is anticipated (whether that reasoning is valid or not is another story). If the number of indentation levels is the issue, consider internal methods with a contract of not accepting null values.
Happy coding.
It is an extremely bad practice to use exceptions for ordinary control flow. The try-catch variant can be up to 1000 times slower than with the null checks due to stack unwinding.

When is handling a null pointer/reference exception preferred over doing a null check?

I have an odd question that I have always thought about, but could never see a practical use for. I'm looking to see if there would be enough justification for this.
When is handling a null pointer/reference exception preferred over doing a null check? If at all.
This applies to any language that has to deal with null pointers/references which has exception handling features.
My usual response to this would be to perform a null check before doing anything with the pointer/reference. If non-null, continue like normal and use it. If null, handle the error or raise it.
i.e., (in C#)
string str = null;
if (str == null)
{
// error!
}
else
{
// do stuff
int length = str.Length;
// ...
}
However if we were not to do the check and just blindly use it, an exception would be raised.
string str = null;
int length = str.Length; // oops, NullReferenceException
// ...
Being an exception, we could certainly catch it so nothing is stopping us from doing this (or is there?):
string str = null;
try
{
int length = str.Length; // oops, NullReferenceException
// ...
}
catch (NullReferenceException ex)
{
// but that's ok, we can handle it now
}
Now I admit, it's not the cleanest code, but it's no less working code and I wouldn't do this normally. But is there a design pattern or something where doing this is useful? Perhaps more useful than doing the straight up, null check beforehand.
The only cases where I can imagine this might be useful is in a multi-threaded environment where an unprotected shared variable gets set to null too soon. But how often does that happen? Good code that protects the variables wouldn't have that problem. Or possibly if one was writing a debugger and wanted the exception to be thrown explicitly only to wrap it or whatnot. Maybe an unseen performance benefit or removes the need for other things in the code?
I might have answered some of my questions there but is there any other use to doing this? I'm not looking for, "do this just because we can" kinds of examples or just poorly written code, but practical uses for it. Though I'll be ok with, "there's no practical use for it, do the check."
The problem is that all null pointer exceptions look alike. Any accounting that could be added to indicate which name tripped the exception can't be any more efficient than just checking for null in the first place.
If you expect the value to not be null, then there is no point in doing any checks. But when accepting arguments, for example, it makes sense to test the arguments that you require to be non-null and throw ArgumentNullExceptions as appropriate.
This is preferred for two reasons:
Typically you would use the one-string form of the ArgumentNullException constructor, passing in the argument name. This gives very useful information during debugging, as now the person coding knows which argument was null. If your source is not available to them (or if the exception trace was submitted by an end user with no debug symbols installed) it may otherwise be impossible to tell what actually happened. With other exception types you could also specify which variable was null, and this can be very helpful information.
Catching a null dereference is one of the most expensive operations that the CLR can perform, and this could have a severe performance impact if your code is throwing a lot of NullReferenceExceptions. Testing for nullity and doing something else about it (even throwing an exception!) is a cheaper operation. (A similar principle is that if you declare a catch block with the explicit intent of catching NREs, you are doing something wrong somewhere else and you should fix it there instead of using try/catch. Catching NREs should never be an integral part of any algorithm.)
That being said, don't litter your code with null tests in places you don't ever expect null values. But if there is a chance a reference variable might be null (for example if the reference is supplied by external code) then you should always test.
I've been programming Java for more than 10 years, and I can't remember a single time I've explicitly tried to catch a null pointer exception.
Either the variable is expected to be null sometimes (for example an optional attribute of an object), in which case I need to test for null (obj.attr != null), or I expect the variable to be not null at all times (in which case a null indicates a bug elsewhere in the code). If I'm writing a method (say isUpperCase) whose argument (String s) is null, I explicitly test for null and then throw an IllegalArgumentException.
What I never ever do, is silently recover from a null. If a method should return the number of upper case characters in a string and the passed argument was null, I would never "hide" it by silently return 0 and thus masking a potential bug.
Personnally (doing C++), unless there is a STRONG contract that assures me that my pointers are not nullptr, I always test them, and return error, or silently return if this is allowed.
In Objective-C you can safely do anything with nil you can do with a non-nil and the nil ends up being a noop. This turns out to be surprisingly convenient. A lot less boilerplate null checking, and exceptions are reserved for truly exceptional circumstances. Or would that be considered sloppy coding?

Should functions that only output return anything?

I'm rewriting a series of PHP functions to a container class. Many of these functions do a bit of processing, but in the end, just echo content to STDOUT.
My question is: should I have a return value within these functions? Is there a "best practice" as far as this is concerned?
In systems that report errors primarily through exceptions, don't return a return value if there isn't a natural one.
In systems that use return values to indicate errors, it's useful to have all functions return the error code. That way, a user can simply assume that every single function returns an error code and develop a pattern to check them that they follow everywhere. Even if the function can never fail right now, return a success code. That way if a future change makes it possible to have an error, users will already be checking errors instead of implicitly silently ignoring them (and getting really confused why the system is behaving oddly).
Can the processing fail? If so, should the caller know about that? If either of these is no, then I don't see value in a return. However, if the processing can fail, and that can make a difference to the caller, then I'd suggest returning a status or error code.
Do not return a value if there is no value to return. If you have some value you need to convey to the caller, then return it but that doesn't sound like the case in this instance.
I will often "return: true;" in these cases, as it provides a way to check that the function worked. Not sure about best practice though.
Note that in C/C++, the output functions (including printf()) return the number of bytes written, or -1 if this fails. It may be worth investigating this further to see why it's been done like this. I confess that
I'm not sure that writing to stdout could practically fail (unless you actively close your STDOUT stream)
I've never seen anyone collect this value, let alone do anything with it.
Note that this is distinct from writing to file streams - I'm not counting stream redirection in the shell.
To do the "correct" thing, if the point of the method is only to print the data, then it shouldn't return anything.
In practice, I often find that having such functions return the text that they've just printed can often be useful (sometimes you also want to send an error message via email or feed it to some other function).
In the end, the choice is yours. I'd say it depends on how much of a "purist" you are about such things.
You should just:
return;
In my opinion the SRP (single responsibility principle) is applicable for methods/functions as well, and not only for objects. One method should do one thing, if it outputs data it shouldn't do any data processing - if it doesn't do processing it shouldn't return data.
There is no need to return anything, or indeed to have a return statement. It's effectively a void function, and it's comprehensible enough that these have no return value. Putting in a 'return;' solely to have a return statement is noise for the sake of pedantry.