14.01.2020 Views

ABAP_to_the_Future

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

7

Exception Classes and Design by Contract

CATCH ycx_monster_exception INTO lcx_monster_exception.

handle_this_exception( lcx_monster_exception ).

CATCH ycx_monster_exception_mc

INTO lcx_monster_exception_mc.

handle_that_exception( lcx_monster_exception_mc ).

CLEANUP.

cleanup_main_method( ).

ENDTRY.

Listing 7.3 TRY/CATCH/CLEANUP

In Listing 7.3, you’re passing the exception object into the HANDLE_THIS_EXCEP-

TION method. Because this is just a standa rd instance of an ABAP class, you can

query all the class attributes in your handler method (e.g., get the error text and

any supplementary data). Meanwhile, to raise the exception in the first place, you

would write code similar to that in Listing 7.4 inside the DO_SOMETHING method.

RAISE EXCEPTION TYPE zcx_monster_exceptions

EXPORTING

wibbly_wobbly_woos = ld_www_count.

Listing 7.4 Exporting Vital Information while Raising an Exception

7.2.4 Cleaning Up after the Exception Is Raised

The CLEANUP command seems to be one of the most widely misunderstood parts

of the whole class-based exception fram ework. Many progra mmers try it once,

conclude it doesn’t work, and then never look at it again. The idea behind the

CLEANUP construct is that at the start of any given routine, the data is in a consistent

state. The routine merrily starts changing some data values, making the data

temporarily inconsistent, and if all goes well the routine will fix up the data again

before the routine finishes. However, if an error occurs halfway through the routine,

then the second half (which fixes up the data) never happens.

Consider the code in Listing 7.5, which is all about conducting an operation to

replace a monster’s head with a new one. If something goes wrong during the

operation (e.g., a power failure), then whatyou want is to abort the operation and

reattach the old head.

METHOD head_swap_operation.

TRY .

mo_monster->remove_current_head( ).

268

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

Saved successfully!

Ooh no, something went wrong!