Wednesday, September 7, 2011

Best Way to Handle Exceptions in ABAP Classes

I've been wanting to switch to exception classes for years but have found them overly cumbersome in most cases.  I've finally figured it out.  Here is a simple way to handle simple exceptions using ABAP exception classes from NetWeaver 6.40 and up.

1. Message Class

Make sure you have a message class for custom messages (SE91) with the required message in it

2. Exception Class

Create an exception class in SE80 e.g. ZCX_ERROR

For anyone without a PhD in computer science, or constrained by budget or time, inherit from CX_STATIC_CHECK.

In class type, select Exception Class and check the With Message Class option box.

3. Create a specific exception.

a. If you want parameters in your exception message create them as attributes in the exception class - e.g. FILE_ERROR_NO
b. Click the texts tab and create an Exception ID - e.g. FILE_ERROR
c. Click the Message Text button and link your Exception ID to a corresponding message in the message class.  You can also bind any message attributes (use & in the message text) to the corresponding exception attributes

That's it.  You are now ready to handle this exception with a single line of code in the CATCH.

4. Raise the exception in your code

  data lo_ex type ref to zcx_error.

  try.


     write: / 'Oops'.
     raise exception type zcx_error
        exporting textid = zcx_error=>file_error
                  file_error_no = 
100.


  catch zcx_error into lo_ex.


      message lo_ex type 'E'.


  endtry.





Your MESSAGE is displayed automatically, with the attribute values inserted.   There are no calls to get_text() or get_longtext(), and no data declarations for the resulting message string.

This means a lot fewer references to SY-SUBRC in my code from now on.


Credits:

Thanks to James Wood for putting me on the right track in his book OO Programming with ABAP Objects, although he doesn't quite nail it. Keller and Kruger don't even get close  in their 2011 ABAP Objects book.

2 comments:

yektek training said...

nice post thanks for sharing from Swathi

Unknown said...
This comment has been removed by the author.