Skip to content

Can You Catch?

This came up recently on the forums and I thought it good to share. Do you see what is wrong with the following code?

Function foo() As FolderItem
  try
    beep
  catch NilObjectException
    return nil
  end try
End Function

I’d guess that most folks would think this code is OK and that NilObjectExceptions would be caught. However, most folks would be wrong. This actually catches ALL exceptions into a variable named NilObjectException.

I’d encourage everyone to write that code as follows – so you have an explicit name for the variable and type for the exception:

Function foo() As FolderItem
  try
    beep
  catch exc as NilObjectException
     return nil
  end try
End Function