When I'm working on a project in the IDE, I always leave the 'Break On Exceptions' menu item checked. I'm the kind of programmer whom is afraid of missing a special and random exception condition when running a project in the debugger. I just can't help it, even if it proved useful only once or twice since I'm using Xojo® ( REALbasic 2.1 actually ). The counterpart is that each time an exception is raised, the debugger kicks in. Even if this exception condition is expected and properly handled. Fortunately, there is a pragma that can help. Here is the syntax:

#pragma BreakOnExceptions On | Off | Default

Let's see an example with a simple CreateFile() function that takes a FolderItem as parameter and returns a boolean that is True if the creation was successful, and False if it wasn't:

Function CreateFile(inFile As FolderItem) As Boolean

  // Create the binary stream
  Dim theStream As BinaryStream

  Try
    theStream = BinaryStream.Create( theFile )

  Catch theIOException As IOException

    // Do some logging
    System.DebugLog CurrentMethodName + ":Failed to create" + theFile.ShellPath

    // Inform the caller that it failed
    Return False

  End Try

  // Write to the stream
  theStream.Write "Some data"
  
  // test for write error
  // [...]
  
  // Close the file.
  theStream.Close

  // the creation was successful
  Return True

End Function

If you're testing a batch process of dozens or hundreds of files for which some exceptions can occur, you don't want the debugger to kick in each time. So I'm doing this:

Function CreateFile(inFile As FolderItem) As Boolean
	  
  // Create the binary stream
  Dim theStream As BinaryStream
  
  #pragma BreakOnExceptions Off '<--- added a pragma
  
  Try
    theStream = BinaryStream.Create( theFile )

  Catch theIOException As IOException

    // Do some logging
    System.DebugLog CurrentMethodName + ":Failed to create" + theFile.ShellPath

    // Inform the caller that it failed
    Return False

  End Try
  
  #pragma BreakOnExceptions Default '<--- added a pragma
  
  // Write to the stream
  theStream.Write "Some data"
  
  // test for write error
  // [...]
  
  // Close the file.
  theStream.Close

  // the creation was successful
  Return True
  
End Function

With these pragma commands, the debugger won't show up whenever an IOException is raised during the BinaryStream creation attempt. And if you need to know about the file paths that failed to be created, you can list them in Mac OS X console, Windows' debugger or Linux's StdErr . You can even log the IOException.ErrorNumber property's value for more information on why it failed.

Now, by using this pragma wherever the code properly handles exceptions, you can concentrate on real unexpected exception conditions.

Leave a Reply

Your email address will not be published. Required fields are marked *

eight + two =