14.01.2020 Views

ABAP_to_the_Future

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Designing Exception Classes 7.2

* Code to do assorted operation type activities

mo_monster->add_new_head( ).

CATCH zcx_power_failure.

mo_candle->light( ).

CLEANUP.

mo_monster->reattach_old_head( ).

ENDTRY.

ENDMETHOD. "Head Swap Operation

Listing 7.5 Head Swap Operations

Looking at the code, you would expect that the CLEANUP code would reattach the

old head before moving on to the CATCH code and lighting the candle. However,

that’s not what happens. If the ZCX_POWER_FAILURE exception is raised in between

removing the current head and attaching a new head, then the CLEANUP code is

ignored. This means that the candle is lit, but the monster is left without a head.

Not good!

This is because the CLEANUP block is only called if the exception is propagated outside

of the current routine (here, HEAD_SWAP_OPERATION) and handled in another

routine. In this example, the ZCX_POWER_FAILURE exception is handled inside the

routine in which the except ion is raised, and so the CLEANUP block is not called.

One way to get around this problem is to add some code to the end of the routine

(outside the TRY/CATCH block) to test for data being in an inconsistent state (e.g.,

monster with no head) and correct the situation. This is shown in Listing 7.6.

CATCH zcx_power_failure.

mo_candle->light( ).

CLEANUP.

"In case an exception is raised which is

"not caught inside this routine

mo_monster->reattach_old_head( ).

ENDTRY.

"In case an exception is caught within this

"routine before the new head is attached

IF mo_monster->number_of_heads = 0.

mo_monster->reattach_old_head( ).

ENDIF.

ENDMETHOD."Head Swap Operation

Listing 7.6 Making 100% Sure a Method Cleans Up After an Exception

269

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!