Re: Nesting try blocks inside catch
On 24 Jan 2006 11:46:11 -0800, "iftekhar" <ahmed.iftekhar@gmail.com>
wrote:
[color=blue]
>hi there ,
>
>consider the followinf code
>#include <iostream>
>#include <stdexcept>
>
>using namespace std;
>
>int main (void)
>{[/color]
// *** TRY _BLOCK A, any exception will be catched by CATCH_BLOCK_A_#[color=blue]
> try
> {
> int i = 5;
> throw i;
> }[/color]
// *** CATCH_BLOCK_A_1 will catch only from TRY_BLOCK_A[color=blue]
> catch (int j)
> {[/color]
// *** TRY _BLOCK B, any exception will be catched by CATCH_BLOCK_B[color=blue]
> try
> {
> double d = 4.5;
> throw d;
> }[/color]
// *** CATCH_BLOCK_B will catch only from TRY_BLOCK_B[color=blue]
> catch(...)
> {
> cout << "got d" << endl;[/color]
// *** TRY _BLOCK C, any exception will be catched by CATCH_BLOCK_C[color=blue]
> try
> {
> int k = 5;
> throw k;
> }[/color]
// *** CATCH_BLOCK_C will catch only from TRY_BLOCK_C[color=blue]
> catch (...)
> {
> float f = 5.5;
> throw f;
> }
> }
> }[/color]
// *** CATCH_BLOCK_A_2 will catch only from TRY_BLOCK_A[color=blue]
> catch(float g)
> {
> cout << "got float g" << endl;
> }[/color]
// *** CATCH_BLOCK_A_3 will catch only from TRY_BLOCK_A[color=blue]
> catch (...)
> {
> cout << "unknown error" << endl;
> }
> cout << "done" << endl;
>}
>compiled with gcc version 3.2.3 20030502 (Red Hat Linux 3.2.3-52)
>
>
>I expected the output of the program to be
>got d
>got float g
>done
>
>but the output is just
>got d[/color]
<snip>[color=blue]
>[/color]
As I hope that comments inserted will make clear, catches are assigned
to tries. Once yopu are inside a catch, you are *outside* of the
corresponding try. So your exception "i" exits TRY_BLOCK_A and enters
CATCH_BLOCK_A_1. Exception "d" is thrown, thus exiting TRY_BLOCK_B and
entering CATCH_BLOCK_B ("got d"). Exception "k" is thrown, exiting
TRY_BLOCK_ C and entering CATCH_BLOCK_C. Exception "f" is thrown, and
as there is no try block surrounding it, it is an unhandled exception.
Rememeber: To be catched, an exception must be *surrounded* by a try
block. When one is in a catch block, then it is outside of its
corresponding try block.
This is atndard, it si not compiler dependent.
Best regards,
Zara |