goto instead of try and catch

Does anyone know how does the C++ exception handling with throw and catch differ from goto to the catch clause? or can we replace try catch with goto?
Here is a good reference for try and catch statements

http://www.cplusplus.com/doc/tutorial/exceptions/

Here is a good reference for the goto statement

http://www.cplusplus.com/doc/tutorial/control/

As for your question I am not really sure what you are asking because goto and try/catch are completely different things that shouldn't be used interchangeably.
i meant can't we just use goto to the catch clause instead doing try catch?
No, for a couple of reasons:
1) catch doesn't have a label that can be the target of a goto.
2) catch has a signature indicating the type of exception it is expecting. You have no way of specifying this if you were to use goto.

Last edited on
Internally (underneath) there are a number of different ways to implement try..catch blocks. The most common is actually a form of goto with some extra housekeeping added in, called SJLJ (for setjmp()/longjmp(), the functions used to do it).

The problem with that method is that anything that must be protected requires some initialization and finalization code to run -- even if no exceptions are thrown.

Unless you have hard profiler proof that it is significantly impacting your code, though, it's not an issue.

Outside the Windows world, there is Dwarf 2, which does not require any per-block initialization/finalization. Instead, the compiler generates tables of data that the exception handling code uses to unwind things gracefully.

Windows systems use Structured Exception Handling (SEH), which plies hardware support for exceptions.


As to the question about using goto instead:

1. Yes, you could do that. In fact, C90 stuff exists to do just that. (Google around "exceptions in c" and "try catch in c" -- most of what you find will walk through using SJLJ, but you can find stuff that just uses goto and a bunch of macros.)

2. Don't do it. It requires more work on your part (both thinking and coding) and is much more brittle than anything the language provides.

Hope this helps.
Topic archived. No new replies allowed.