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

PERFORM unlock_monster USING mo_chosen_monster.

ENDFORM."User Command

Listing 7.2 Using a NO_CHECK Exception During User Command Processing

In the preceding example, ZCX_BC_USER_CANCELLED inherits from CX_NO_CHECK.

Almost every one of the 15 possible user commands shows the user one or more

Are you sure? pop-up boxes, any of which the user can cancel out of, aborting

the whole process, and the code that ca lls the pop-ups can be many levels down

the call stack from the USER_COMMAND routine.

Traditionally, in order to deal with users deciding to cancel processing, you’d

have to declare a global variable called GF_CANCEL or some such, and after coming

back from each of the 15 different po p-up boxes you’d have a check, like CHECK

GF_CANCEL = ABAP_FALSE , and would repeat this statement at every level in the

call stack. Remember, for some user co mmands you might show the user three

different sorts of pop-up boxes, one after the other, any one of which the user can

cancel out of.

However, the code in Listing 7.2 takes a different approach: the instant the user

clicks a Cancel button, you raise the ZCX_BC_USER_CANCELLED exception, and the

program flow jumps right back to the top of the call stack, unlocks the monster,

and you’re done. This prevents the code from being littered with checks for the

same thing.

In conclusion, CX_NO_CHECK seems ideal when your routine has no idea what to do

with the problem encountered and you want to pass the error information

upwards until some part of the program does know how to respond.

7.1.4 Deciding which Type of Exception Class to Use

Many people are trying to work out which of the three types of exception class to

use in what situation, and most documentation on the subject is very vague.

There are no hard and fast rules, but Figure 7.1 is a little decision tree to help you

decide what type of exception class to use.

For example, imagine you have created a pu blic method in a global class that is

going to be reused all over the place. If this method gets into trouble when an

exceptional situation comes along and ca nnot handle the problem locally, then

262

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

Saved successfully!

Ooh no, something went wrong!