Tracking Down Exception Errors With objc_exception_throw

When an application throws an exception, there is debug information shown in the console – below is the output in the console for an NSInvalidArgumentException:

Although helpful, depending on the size of your application, it may take quite some time to find the offending code. One way to better track exceptions is to catch them, as shown in this post Try, Catch and Finally. However, wrapping every potential condition is not always practical. There is another way to track down exception errors.

With a symbolic breakpoint, we can force the runtime to stop on the line of code that is generating the exception. Select the breakpoint tab (in the Project navigator) and tap the + in the lower left corner to create a new symbolic breakpoint. Enter objc_exception_throw for the Symbol as shown below:

When you run the application with the symbolic breakpoint enabled, the code will stop at the offending line:

Notice in the console the reference to obj_exception_throw and Pending breakpoint – the debugger stops before the actual line of code executed.

When you experience an exception that is not wrapped in a try/catch block, give the symbolic breakpoint a go.

  1. When you’re using the plus-button down there you might just as well select “Add Exception Breakpoint…” instead of “Add Symbolic Breakpoint…”. Aside from not having to type the “obj_exception_throw” yourself, this has two advantages: 1) you can also catch C++ exceptions and 2) you can choose whether to stop when the exception is thrown (as does the solution in this blog entry) or when the exception is caught (helps you debug your catching code).

  2. We need more posts like this! Code posts are a dime a dozen nowadays, but there is no repository for great information like this.

  3. You can also just choose “Add Exception Breakpoint” after tapping the “+”.

    Note that if you have a different exception that is frequently thrown and caught, you will want to disable the breakpoint when not actively tracking down a crash, because the exception breakpoint doesn’t know enough

    An interesting follow-up article would be to examine all of the different things that you can do after hitting the exception breakpoint, including traversing the call stack using the Debug Navigator (cmd-5) and looking at the values that led up to the crash, or noting which thread the crash occurred in.

    Also, I’ve never really tried specifying actions to take when the exception is hit (see Action: Click to add an action) in the Add Exception Breakpoint dialog). Do you have any favorites? Maybe “Debugger Command: bt” to get the call stack?

    Anyway, great article — thanks John, all of your stuff is helpful and well written.

  4. Amazing! Simply amazing! Where do you learn these things?? Thank you very much for sharing all this knowledge! Today I’ve learned a lot!! :D

Comments are closed.