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

related to any internal implementation details of the method that raises the

exception). The caller does n’t need to know how the called routine works, just

that it failed in some wa y; therefore, a name like CX_NO_RECORD_FOUND is better

than CX_READ_ON_TABLE_XYZ_FAILED.

7.2.3 Raising the Exception

In traditional function modules, exceptions were raised via the RAISE EXCEPTION

construct. Now, there is the obviously better RAISE EXCEPTION TYPE construct.

(It’s obviously better because it has one more word and is close enough to the old

syntax to thoroughly confuse everyone.)

In order to raise class-based exceptions using the new RAISE EXCEPTION TYPE construct,

you need to have a TRY/CATCH/CLEANUP block, which some traditional ABAP

programmers don’t like the look of, because it seems much more complicated

than just saying IF SY-SUBRC <> 0. An example of catching a class-based exception

is shown in Listing 7.3; as you can see, there are no commands that do anything;

it just describes the structure of the error handling block. Each section has

a clear task to do, and in each section yo u call a method to do that section’s task

(i.e., the proper pu rpose of the method or error handling or cleaning up). This

approach obeys the wise words of one of the fathers of OO programming, Robert

Martin, who once said, “Each method sh ould do one thing only, and error handling

is one thing.”

Thus, there is a clear separation of concerns. In Listing 7.3, the DO_SOMETHING

method does the real work of the application and cares not about how errors are

handled. The HANDLE_THIS_EXCEPTION method, on the other hand, is solely concerned

about handling an error and cares not about the real business of the application.

You should always aim for this approach when writing TRY/CATCH/CLEANUP

blocks.

METHOD main.

* Local Variables

DATA: lcx_monster_exception

TYPE REF TO ycx_monster_exception,

lcx_monster_exception_mc

TYPE REF TO ycx_monster_exception_mc.

TRY.

do_something( ).

267

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

Saved successfully!

Ooh no, something went wrong!