- The most elegant way how to handle exception messages is to have them all stored at one place – ideally in a message class. So the first step will be message class creation (if you don’t already have one) in SE91.
In this message class you can create your desired messages – you can use the most generic message
& & & &
but in our example we’ll use the following:
Material & does not exist
- Now we can step forward to create the exception class itself:
In SE24 create new class of type “Exception” named i.e. ZCX_MY_EXCEPTION derived/inherited (in most cases) from CX_STATIC_CHECK and check the option “With Message Class”
- Note: Step 1 and checking option “With message class” in step 2 can be ommited and texts will be created and stored in the text management OTR. But it is not possible to combine both text variants in one exception class.
- Because we have parameters in our exception messages we have to define these parameters in our exception class. The most generic would be standard MSGV1 – MSGV4
- Now we extend our exception by adding new specific exception IDs. To do that, go to Texts tab and create new exception ID, i.e. MATERIAL_NOT_FOUND and assign it with message class, message number and bind any message attributes (& in the message text) to the corresponding exception attributes.
- Note: If you don’t specify Exception ID when raising the exception then the default exception ID (it has the same name as exception class) is used and it’s text is generated.
- And that’s it!
Now you can simply use your new exception class with specific exception IDs in your program like in the following code:
DATA l_exc TYPE REF TO zcx_my_exception. TRY. * Exception thrown RAISE EXCEPTION TYPE zcx_my_exception EXPORTING textid = zcx_my_exception=>material_not_found msgv1 = '1234567'. "material number CATCH zcx_my_exception into l_exc. message l_exc type 'E'. endtry.