Breakpoint on all throws

Answering some Stack Overflow questions as a morning exercise.
Today I found How to set a breakpoint on all throws
question. There’s accepted answer …

This isn’t possible, because throw statements don’t cause exceptions.

If you however call a function that can throw errors with try!
Swift will assert at runtime if the called function actually throws an error.

The debugger will stop at the line that caused the failed
assertion (just as with nil values in implicitly unwrapped optionals).

… which is not correct. How to do it? Read this post or my answer.
Both contain same info.

I have to repeat it – errors thrown in Swift are not exceptions. It’s just another
way of error propagation. Keep this in mind.

How to set breakpoint on all throws?

First thing you can try is to set symbolic breakpoint with throw symbol. Doesn’t work, it’s not a symbol.
Second thing you can try is to set exception breakpoint (even if thrown errors are not exceptions).

There’s no Swift and All doesn’t work. What now? Watch What’s new in LLDB session
and you’ll find that there is a way:

(lldb)br s -E swift

What br s -E does?

-E <language> ( --language-exception <language> )
  Set the breakpoint on exceptions thrown by the specified language
  (without options, on throw but not catch.)

It’s all about exceptions. I agree that this part is little bit misleading, because, again,
thrown errors are not exceptions. It’s also probably the main reason why it’s not in the Xcode
UI yet. They don’t know where to put it? They forgot? Or it’s an issue with low priority for now?
Who knows.

You can put br s -E swift in your ~/.lldbinit to make it working, but that’s
probably not what you really want.

How to set breakpoint on all throws in Xcode?

Add it manually

Set a breakpoint somewhere in your code. When execution pauses, just type br s -E swift
in LLDB prompt and then continue.

Add it automatically

Set a breakpoint somewhere in your code and edit it in this way:

  • put br s -E swift into Action – Debugger Command,
  • enable Automatically continue after evaluating actions.

Toggle this breakpoint (on / off) whenever you do want stop on all throw statements.

Symbolic breakpoint

You can find out that actually there’s symbol for throw when execution pauses.
It’s called swift_willThrow. Thus you can use symbolic breakpoint as well.

Warning: you can expect changes in future betas which can
break it. Probably the safest way is to use breakpoint with debugger
command action which you can toggle on / off.

Breakpoint hit

It looks like this when you hit “throw” breakpoint:

Just select previous stack frame to see where the error was thrown:

So the answer is – yes, you can break on all throws in Swift.