I heard the notion of @throw is expensive in Objective-C, what is the reason behind it? Is throw
in Java also expensive too?

- 16,374
- 12
- 37
- 38
-
2Start with [this answer](http://stackoverflow.com/a/324805/581190) to learn more. – zrzka Jul 05 '15 at 20:34
-
Why do you need to know? – i_am_jorf Jul 05 '15 at 20:45
-
The link from @robertvojta is an excellent starting point. Exceptions in Objective-C are really that: exceptions. I'd bet many programmers don't use them much if at all. As they are designed to catch programming errors, there are often easier constructs like NSAssert to get the job done. – Eiko Jul 05 '15 at 20:49
2 Answers
"Exceptions in Objective C are implemented using the C primitive: longjmp(). Objective-C is not C++. You may have many layers of method call between the code that raises the exception and the method that catches it. It is very easy to write a memory leak."
http://newsgroups.derkeiler.com/Archive/Comp/comp.sys.mac.programmer.help/2007-08/msg00020.html
Also...
"A little more information.
C++ exceptions and, under the modern ABI, Objective-C exceptions are extremely cheap to set up (@try), but expensive to @throw and @catch.
When the @throw happens, there is a heavy cost to generating the bits necessary to properly unwind the stack.
Unfortunately, the AppKit has an issue where it causes the unwind info to be generated as a normal part of its operation (without throwing an exception).
Thus, certain AppKit operations in 64 bit can be quite slow at this time.
b.bum"

- 6,151
- 19
- 83
- 132
Modern Objective-C uses C++ exceptions. While there is a cost associated with throwing a C++ exception, it's hardly prohibitive in most cases.
The reason exceptions are not used with Objective-C is because of memory management.
Languages like Java and C++ have built-in mechanisms for dealing with memory management when an exception is thrown. Objective-C does not (unless you wrap everything in C++ stack objects).
Instead, when you throw
in Objective-C, all strong references inside of the enclosing try
block will simply leak. There are ways to code around that, but it's very complicated and error prone and is therefore unwise in practice.