The advanced half of ABAP Objects: how errors travel through your code (class-based exceptions), how objects notify each other (events), how a program inspects and builds types at runtime (RTTS), and the patterns and tests that keep OO code clean, and what changes for OO code in ABAP Cloud and S/4HANA. Pages 01 and 02 are the basis; the persistence and transaction services at the end are Legacy – know them for interviews, use RAP for new code.
Page at a glance

Part 1 – Class-based exceptions: TRY, CATCH, CLEANUP
An exception is an error situation signalled while the program runs (division by zero, missing table line, flight not found). The runtime creates an exception object – an instance of a class whose name starts with CX_ (SAP) or ZCX_ (yours) – and looks for a handler. Only an exception that nobody handles becomes a runtime error (short dump, ST22).
- Exceptions raised by SAP (e.g.
CX_SY_ZERODIVIDE) are declared and raised by the kernel or by SAP classes; you only handle them. Your own exceptions (ZCX_…) you declare, raise and handle yourself. - TRY encloses the statements that might raise. When an exception occurs, the rest of the TRY block is skipped and control jumps to a matching CATCH.
CATCH cx_a cx_b INTO DATA(lx)– one CATCH may list several classes;INTOgives you the object, so you can calllx->get_text( ),lx->get_longtext( ),lx->get_source_position( )or readlx->previous.- A CATCH for a class also catches all its subclasses. Order CATCH blocks from most specific (subclass) to most general (superclass) – the reverse order is a syntax error, because the later block could never be reached.
- Catching
CX_ROOTis allowed but bad practice: it also swallows programming errors you should fix. Catch the specific class, or the category class at most.
|
CLEANUP – tidy up before the exception moves on
A TRY block can have CATCH blocks and one CLEANUP block (after the CATCHes). CLEANUP runs only when an exception raised in this TRY is not caught here but by an outer handler (an enclosing TRY or a calling method). Use it to restore a consistent state: clear variables, free tables, close files, release locks. CLEANUP INTO lx gives you the exception object.

- CLEANUP must be left normally through ENDTRY so the exception can reach its handler. Statements that leave it early (RETURN, EXIT, CHECK, STOP, LEAVE …, SUBMIT without AND RETURN, LEAVE TO TRANSACTION) are syntax errors or cause a runtime error.
- If no handler exists anywhere, the program dumps at the point of the error and CLEANUP is not run.
- ABAP has no FINALLY. Code that must always run goes after ENDTRY (and into CLEANUP for the propagating case).
Common standard exceptions
Exception class | Raised when |
|---|---|
CX_SY_ZERODIVIDE | Division by zero |
CX_SY_ARITHMETIC_OVERFLOW | Result too large for the target type |
CX_SY_CONVERSION_NO_NUMBER | Text like 'ABC' converted to a number |
CX_SY_ITAB_LINE_NOT_FOUND | Table expression |
CX_SY_REF_IS_INITIAL | Method call or |
CX_SY_MOVE_CAST_ERROR | Down cast |
CX_SY_OPEN_SQL_DB | Database error in ABAP SQL (e.g. duplicate key in INSERT … FROM TABLE) |
CX_SY_DYNAMIC_OSQL_SEMANTICS | Wrong table or field name in dynamic ABAP SQL |
CX_SY_NO_HANDLER | A checked exception left a method without being declared (Part 2) |
Part 2 – Exception categories and RAISING
Every exception class inherits from CX_ROOT through exactly one of three abstract category classes. The category decides whether a method must declare the exception and when this is checked.

CX_STATIC_CHECK | CX_DYNAMIC_CHECK | CX_NO_CHECK | |
|---|---|---|---|
Use for | Errors every caller must expect (application errors) | Errors the caller can avoid by checking preconditions | Errors that usually can't be handled locally |
Declare in RAISING? | Must (if not handled in the method) | Should | Never needed – implicitly declared |
Checked | Compile time: syntax check warning | Runtime: when it leaves a method | Not checked |
Examples | Most custom |
| CX_SY_EXPORT_BUFFER_NO_MEMORY |
RAISING – the exception belongs to the caller
RAISING in a method signature says: this exception may leave the method and propagates to the caller, who handles it (or declares it again). Advantage: each caller reacts in its own way – one shows a message, another logs and continues.
|
- If a STATIC or DYNAMIC exception leaves a method without a RAISING declaration, the runtime raises
CX_SY_NO_HANDLERinstead (catchable; the original exception is in itspreviousattribute). - The signature order is IMPORTING, EXPORTING, CHANGING, RETURNING, then RAISING (or EXCEPTIONS).
- An exception raised in an instance constructor means the object is not created – the reference keeps its previous value.
- Exceptions vs
ASSERT: exceptions are for error situations that can really happen;ASSERTis for conditions that must never be false (a bug) and dumps with ASSERTION_FAILED.
Part 3 – Raising exceptions
Syntax | Since | Use |
|---|---|---|
RAISE EXCEPTION TYPE zcx_x EXPORTING textid = … previous = … | 6.10 | Classic form, still common |
RAISE EXCEPTION NEW zcx_x( … ) | 7.52 | Same, with the NEW operator |
RAISE EXCEPTION lx | 6.10 | Re-raise an existing exception object |
| 7.40 | Raise inside an expression |
RAISE EXCEPTION TYPE zcx_x MESSAGE e001(zmsg) WITH v1 v2 | 7.50 | Text from a message class (Part 4) |
RAISE RESUMABLE EXCEPTION TYPE zcx_x | 7.02 | Caller may continue after RAISE (Part 5) |
| 7.53 | Runtime error with an exception object – cannot be caught (below) |
|
Exception chaining – wrap, don't leak
A layer that calls technical code catches the technical exception and raises its own exception with previous = lx. Callers then handle one exception class of your API, and the original cause is still available for logging.

|
RAISE SHORTDUMP – stop on purpose, with a clear reason (7.53)
Some states are unrecoverable: a mandatory configuration is missing, an internal invariant is broken. RAISE SHORTDUMP ends the program with a runtime error, like an unhandled exception, but on purpose: the short dump (ST22) shows the exception class and its text. It cannot be caught – no TRY block can stop it.
|
- Like any runtime error it ends the program and rolls back the open database changes. Text and attributes come from the exception class, so you can use the same message class texts as for normal exceptions.
Tool | Use it for | Caller can react? |
|---|---|---|
Exception ( | Errors that can really happen and that some caller can handle | Yes – CATCH |
ASSERT condition | A condition that must be true unless there is a bug; dump ASSERTION_FAILED, no own text (checkpoint groups can switch it to a log entry) | No |
RAISE SHORTDUMP | Unrecoverable state where a dump with a precise class and text helps the analysis | No |
MESSAGE … TYPE 'X' | Older way to force a dump (MESSAGE_TYPE_X); no exception object | No |
- Clean ABAP: "Dump for totally unrecoverable situations" – everything else is an exception.
Legacy – classic (non-class-based) exceptions
Older methods and almost all function modules use classic exceptions: declared with EXCEPTIONS, raised with RAISE name (or MESSAGE … RAISING name), handled by checking SY-SUBRC. Know them to call old code; use class-based exceptions in new methods.
|
- One method cannot use both
EXCEPTIONSandRAISING. RAISE nameraises only classic exceptions; class-based exceptions always needRAISE EXCEPTIONorTHROW.
Part 4 – Custom exception classes with message texts
A global exception class is created in SE24 or ADT, named ZCX_…, and inherits from CX_STATIC_CHECK, CX_DYNAMIC_CHECK or CX_NO_CHECK (or from another exception class). It is a repository of related error texts; each text has an exception ID – a constant attribute you pass as textid when raising.
- With message class (recommended): tick "With message class" – the class implements
IF_T100_MESSAGE. Each exception ID points to a message of a message class (SE91 or the ADT message class editor).- The ID constant is a structure of type
SCX_T100KEY:MSGID,MSGNOandATTR1–ATTR4. ATTR1–4 name the class attributes that fill the placeholders&1–&4of the message. - Fill those attributes when raising (constructor parameters with the same names).
- The ID constant is a structure of type
IF_T100_DYN_MSG(7.50): lets you raise with any message directly –RAISE EXCEPTION TYPE zcx_x MESSAGE e001(zmsg) WITH v1 v2– and display it withMESSAGE lx TYPE 'E'. Preferred in new code; ADT's exception class template uses it.- Legacy – OTR texts: the old "Texts" tab with short/long texts from the Online Text Repository. Still found in older classes; not available in ABAP Cloud – use message classes.
|

Errors in RAP: failed and reported instead of RAISE
In a RAP behaviour handler (Part 12) the RAP runtime is your caller, so you don't raise exceptions to it. You report problems in the response parameters and let RAP decide what happens to the transaction.
failed– which instances failed (%tky, optionally%fail-cause).reported– the messages for the UI in%msg, an object of typeIF_ABAP_BEHV_MESSAGE. Create it with the inherited methodsnew_message( … )/new_message_with_text( … ), or with your own exception class that implementsIF_ABAP_BEHV_MESSAGE– then one ZCX class serves classic code and RAP.- Don't let exceptions leave a handler method: catch them and turn them into
failed/reportedentries. Code example in Part 12; details in RAP › 05 · Business Logic & Messages.
Part 5 – RESUMABLE, RESUME and RETRY
Feature | What it does | Syntax |
|---|---|---|
Resumable exception | The handler may let the raising method continue after the RAISE statement (like a warning) |
|
CATCH BEFORE UNWIND | Handler runs before the call stack is cleared – needed for RESUME | CATCH BEFORE UNWIND zcx_x INTO lx |
RESUME | Continue directly after the RAISE in the method | IF lx->is_resumable = abap_true. RESUME. ENDIF. |
RETRY (7.02) | Restart the whole TRY block after fixing the cause |
|

|
Part 6 – Events
An event lets an object announce "something happened" without knowing who reacts. The sender raises the event; any number of handler methods in the same or other classes react – but only if they were registered with SET HANDLER. This is ABAP's built-in observer pattern and the way ALV grids report clicks to your program.

The four steps
- 1. Declare in the sender class (or an interface):
EVENTS name EXPORTING VALUE(p) TYPE t.(instance) orCLASS-EVENTS(static). Only the declaration part of a class or interface can contain events. - 2. Handler method in the same or another class:
METHODS h FOR EVENT name OF lcl_sender IMPORTING p sender.(orCLASS-METHODSfor a static handler). - 3. Register before the event is raised:
SET HANDLER lo_handler->h FOR lo_sender.– the reference before->is the handler object, the reference after FOR is the sender. - 4. Raise inside a method of the sender class:
RAISE EVENT name EXPORTING p = value.
|
Rules
- Handlers are never called directly; without a registration (or with one made after the RAISE) nothing happens – no error either. Registered
FOR lo_bbutlo_araises → the handler does not run either. - Static handler (
CLASS-METHODS … FOR EVENT): register it with the class name –SET HANDLER lcl_log=>on_overdrawn FOR lo_account.(instance event) orSET HANDLER lcl_log=>on_static_evt.(static event, no FOR). - Event parameters are EXPORTING only and always passed by value; the handler imports them under the same names. Mandatory parameters must be supplied in RAISE EVENT.
- Every instance event has the implicit parameter
SENDER– a reference to the raising object. Import it when one handler serves many senders. - Handler visibility rule: the visibility section of the handler method cannot be more general than that of the event (SAP keyword documentation). A PRIVATE handler for a PUBLIC event is fine; a PUBLIC handler for a PRIVATE event is a syntax error. The handler's visibility also decides who may register it with SET HANDLER.
- Handler IMPORTING lists only names – no TYPE/LIKE, OPTIONAL or DEFAULT (the types come from the event), and it may import just some of the event's parameters.
- When an event has several handlers, they run one after another (in practice in registration order – don't build logic on the order). Control returns to the statement after RAISE EVENT.
ACTIVATION 'X'(the default) registers,ACTIVATION abap_false(space) deregisters.- Registered handlers stay alive: while an instance handler is registered for an instance event, the runtime still uses the handler object, so the garbage collector does not delete it – even if your program has no reference to it any more. It becomes collectable only after deregistration (
ACTIVATION abap_false) or when all raising objects are gone. Deregister handlers you no longer need in long-running programs.
Instance event | Static event | |
|---|---|---|
Declared with | EVENTS | CLASS-EVENTS |
Raised in | Instance methods of the class only | Instance or static methods of the class |
Implicit SENDER | Yes | No |
Registration |
|
|
Handler method | Instance or static | Instance or static |
- Visibility: the event's section decides where handlers can be declared – public: anywhere; protected: the class and its subclasses; private: only the class itself (private events are not visible in subclasses).
SET HANDLERcan be written wherever the handler method is visible. - Events in interfaces:
EVENTS einINTERFACE zif_x; the implementing class raisesRAISE EVENT zif_x~e; handlers are declaredFOR EVENT e OF zif_xand react to every implementing class. - Standard events: SAP classes raise events, you only handle them – e.g.
CL_SALV_TABLE(get_event( )→double_click,link_click,added_function) andCL_GUI_ALV_GRID(double_click,hotspot_click,toolbar,user_command,data_changed). See page 04 ALV Reporting. - RAP business events are the RAP counterpart: declared in the behaviour definition, raised with
RAISE ENTITY EVENTduring the save sequence (saver class, Part 12) and consumed decoupled from the sender. See RAP › 10 · Business Events & Event-Driven RAP.
Part 7 – RTTS: RTTI and RTTC
RTTS (Run Time Type Services) describes and creates types while the program runs. It has two parts:
- RTTI (Run Time Type Identification): read the definition of a type, variable or object – the
describe_…methods. - RTTC (Run Time Type Creation): build new types dynamically – the
get( )/create( )methods – and create data objects withCREATE DATA … TYPE HANDLE.

CL_ABAP_ENUMDESCR(enumerated types, 7.51) is a subclass of ELEMDESCR.
RTTI method | Gives you |
|---|---|
cl_abap_typedescr=>describe_by_name( 'SFLIGHT' ) | Description of a DDIC or program type by name |
cl_abap_typedescr=>describe_by_data( lv_x ) | Description of a variable's type |
cl_abap_typedescr=>describe_by_data_ref( lr_x ) | Type of the data a reference points to |
cl_abap_typedescr=>describe_by_object_ref( lo_x ) | Class of an object → |
| Fields of a structure |
lo_struct->get_ddic_field_list( ) | DDIC field info incl. texts |
CAST cl_abap_classdescr( cl_abap_typedescr=>describe_by_name( 'ZCL_X' ) ) | A class: |
|
CREATE DATA … TYPE HANDLEneeds a data reference (TYPE REF TO data) and a handle whose static type isCL_ABAP_DATADESCRor a subclass (struct, table, elem, ref descr).cl_abap_tabledescr=>create( line_type )returns the table description object.
Example: display any allowed table dynamically (safe version)
The classic RTTS exercise: the user enters a table name, the program builds a matching internal table and shows its rows. Reading any table the user types would be a serious security hole (it bypasses table authorizations). This version validates the name against an allow-list and runs an authority check before reading.
|
- Shortcut without RTTS:
CREATE DATA lr_table TYPE STANDARD TABLE OF (p_tab).– the same result in one line. RTTS is needed when you build types that exist nowhere in the dictionary. describe_by_nameraises the classic exceptionTYPE_NOT_FOUNDfor an unknown name – a functional call can't catch it and dumps. The allow-list prevents that; otherwise call it withEXCEPTIONS type_not_found = 1.- For free-text names use
CL_ABAP_DYN_PRG(e.g.check_table_name_str) to validate, never concatenate user input into dynamic SQL.CL_ABAP_TABLEDESCR=>GETis the cached alternative toCREATE.
Part 8 – More runtime services: serialisation, weak references, shared objects
Three services of the ABAP runtime that change how long an object lives and where it can go: into a string (serialisation), out of memory when nobody needs it (weak references), or into memory shared by many sessions (shared objects).
Serialising objects (asXML)
Serialising turns an object into a string you can store or send; deserialising builds a new object with the same state from it. CALL TRANSFORMATION id does both, using SAP's canonical XML format asXML.
- The class must implement the tag interface
IF_SERIALIZABLE_OBJECT(it has no methods). For other classes the object is written without its attributes. - By default all instance attributes are written, including private ones; static attributes are not. Referenced objects are serialised with it, so a whole object graph can travel.
- To control the output, declare the private instance methods
SERIALIZE_HELPERandDESERIALIZE_HELPER; then the attributes of that class part are no longer written automatically.
|
- Uses: keep object state in a database table or a background job's parameters, or make a deep copy of an object graph.
- JSON: for data (structures, tables) use
CALL TRANSFORMATION idwith a JSON writer (cl_sxml_string_writer=>create( type = if_sxml=>co_xt_json )) orxco_cp_json(Part 12). The popular /UI2/CL_JSON is also released for ABAP Cloud. - ABAP Cloud: check on your release whether
IF_SERIALIZABLE_OBJECTis released before relying on object serialisation there.
Weak references
A normal (strong) reference keeps its object alive. A weak reference – an object of CL_ABAP_WEAK_REFERENCE – points to an object without keeping it alive. When no strong reference is left, the garbage collector may delete the object; get( ) then returns an initial reference.
|
- Use it for caches and registries that must not stop memory from being freed. The runtime decides when the garbage collector runs, so never rely on the moment.
CL_ABAP_SOFT_REFERENCEexists as well; it currently behaves like the weak reference.
Shared objects – objects in shared memory
Objects normally live in one internal session. Shared objects live in the shared memory of the application server, so many programs and users read the same object – e.g. a large buffer of rates – without loading it again. The full topic (SHMA, locks, versions, monitor SHMM) is on CORE ABAP › 14; here is the OO view.
- Area (transaction SHMA): its name is the name of the generated area class, a subclass of
CL_SHM_AREA. Its static methodsattach_for_write( )/attach_for_read( )return an area handle. - Root class: an ordinary global class declared with
SHARED MEMORY ENABLED; its object is the entry point to the data in the area. - Objects in the area are created with
CREATE OBJECT … AREA HANDLE–NEWhas no such addition.
|
- Wrap attach calls in TRY … CATCH
cx_shm_attach_error(e.g. no active version yet, or locked). - A classic on-premise technique; check your release before planning it for ABAP Cloud.
Part 9 – Design patterns
A design pattern is a proven, reusable solution to a recurring design problem. The three you must be able to code or explain in an ABAP interview are singleton, factory and MVC.

Singleton – exactly one instance
CREATE PRIVATE stops everyone else from using NEW; a static method hands out the one instance, stored in a static attribute. Make the class FINAL (a subclass of a CREATE PRIVATE class could not be instantiated anyway). The instance lives once per internal session. Example in SAP: the agent classes of the persistence service (Part 14). Clean ABAP: make singletons only where several instances really make no sense – a singleton is hard to replace in a unit test.
|
Factory – hide how objects are created
A factory method decides which class to instantiate and returns it as an interface (or superclass) reference. Callers depend only on the interface; adding a new variant changes the factory, not the callers. SAP's best-known example: CL_SALV_TABLE=>FACTORY.
|
MVC – Model, View, Controller
MVC separates business logic from presentation, so either can change without breaking the other.
Part | Responsibility | ABAP examples |
|---|---|---|
Model | Data and business rules – reads/changes the database | Model class, CDS views, RAP business object |
View | Shows the output to the user | ALV, Smart Form, classical list, Fiori UI |
Controller | Receives user actions, calls the model, picks the view | Report/event handler class, Web Dynpro controller, OData service |
The same model can feed an ALV, a form and a classical list. SAP frameworks built on MVC: Web Dynpro ABAP, BSP, and SAPUI5/Fiori with OData or RAP as the model.
Other patterns worth naming
Pattern | Idea | ABAP example |
|---|---|---|
Observer | Objects subscribe to changes of another object | Events + SET HANDLER (Part 6) |
Facade | One simple class in front of a complex subsystem | Wrapper class around several BAPIs |
Strategy | Swap an algorithm behind an interface | Different pricing classes implementing one interface |
Decorator | Add behaviour by wrapping an object with the same interface | Logging wrapper around a data-access class |
Adapter | Make an incompatible interface fit | Class that maps an old FM to a new interface |
Dependency injection | Pass dependencies in (constructor) instead of creating them inside | Inject a test double in ABAP Unit (Part 11) |
Part 10 – SOLID and Clean ABAP
SOLID principles
Principle | Meaning | In ABAP |
|---|---|---|
S – Single responsibility | A class has one reason to change | Separate data access, logic and output classes instead of one huge report class |
O – Open/closed | Open for extension, closed for modification | New variant = new subclass or interface implementation, not another IF/CASE branch |
L – Liskov substitution | A subclass must work wherever the superclass is expected | Redefinitions keep the contract (same meaning, no new mandatory preconditions) |
I – Interface segregation | Many small interfaces beat one big one |
|
D – Dependency inversion | Depend on abstractions, not concrete classes | Type attributes as |
Clean ABAP rules for classes, methods and exceptions
Clean ABAP is SAP's open style guide for ABAP (github.com/SAP/styleguides). Interviewers like to ask for its OO rules; the rule names below are the guide's own headings.
Area | Rule | Why |
|---|---|---|
Classes | FINAL if not designed for inheritance | Inheritance is a contract; open it only on purpose |
Classes | Members PRIVATE by default, PROTECTED only if needed | Small public surface, free to change |
Classes | Prefer objects to static classes; prefer instance to static methods | Static calls can't be replaced by a test double |
Classes | Prefer composition to inheritance (page 02) | Looser coupling than a deep class tree |
Classes | Public instance methods should be part of an interface | Callers and tests depend on the interface (dependency inversion) |
Classes | Prefer | Shorter; CREATE OBJECT only for dynamic types |
Classes | If your global class is CREATE PRIVATE, leave the CONSTRUCTOR public | Needed for correct compilation and syntax checks of global classes |
Methods | Few IMPORTING parameters (at best less than three); split methods instead of adding OPTIONAL or Boolean parameters | One method, one job |
Methods | Prefer RETURNING to EXPORTING; RETURN, EXPORT or CHANGE exactly one parameter – never a mix | Functional calls, readable call sites |
Methods | Consider calling the RETURNING parameter | The guide prefers |
Methods | Do one thing, keep methods small, fail fast | Easy to read and to test |
Exceptions | Prefer exceptions to return codes; use class-based exceptions | Errors can't slip through |
Exceptions | Use own super classes; throw one type of exception, sub-classes to distinguish cases | Callers catch one class per API |
Exceptions | CX_STATIC_CHECK for manageable, CX_NO_CHECK for usually unrecoverable, consider CX_DYNAMIC_CHECK for avoidable errors | Matches the categories in Part 2 |
Exceptions | Dump for totally unrecoverable situations; prefer | RAISE SHORTDUMP, Part 3 |
Exceptions | Wrap foreign exceptions instead of letting them invade your code | Chaining with |
- Prefixes (
iv_,rv_,lo_…) are still the convention in many projects and on this page. Know both views: follow your project's naming rules, and cite Clean ABAP when asked what SAP recommends. RETURN expr(7.58): in a functional method,RETURN expr.assigns the value to the RETURNING parameter and leaves the method in one statement (details on page 01 Part 5).
|
- Testing rules of the guide (given-when-then, one "when" per test, test seams only as a workaround) follow in Part 11.
Part 11 – ABAP Unit, injection and test doubles
ABAP Unit is the built-in unit test framework. Tests are local test classes in the test include of a global class (ADT tab "Test Classes", SE24 Goto → Local Definitions/Implementations → Local Test Classes) or in a program. They are transported with the class, but not generated or run in production systems (system setting, profile parameter abap/test_generation).
- Test class:
CLASS ltc_x DEFINITION FINAL FOR TESTING RISK LEVEL HARMLESS DURATION SHORT.- RISK LEVEL: HARMLESS (no persistent changes), DANGEROUS (changes data), CRITICAL (changes settings or customizing). The system setting decides which levels may run. Without the addition a test class counts as CRITICAL – the default – so always state the level.
- DURATION: SHORT, MEDIUM, LONG – the time limits are set per system (transaction SAUNIT_CLIENT_SETUP).
- Test methods:
METHODS test_name FOR TESTING.– normal, concrete instance methods without parameters, private by convention. They are not abstract. - Fixture methods (fixed names, all optional):
class_setup/class_teardown(static, once per class),setup/teardown(before / after each test method). - Structure each test as given – when – then: prepare the class under test and its doubles, make exactly one call of the code under test, then check the result with assertions.
- Assertions in
CL_ABAP_UNIT_ASSERT:assert_equals( act = … exp = … msg = … ),assert_true,assert_false,assert_initial,assert_not_initial,assert_bound,assert_differs,fail( ). CLASS zcl_x DEFINITION LOCAL FRIENDS ltc_x.in the test include lets the test reach private components.- Run: Ctrl+Shift+F10 in ADT (or SE24/SE80 → Test → Unit Test), with coverage via Coverage As; ATC runs them too.

|
Test doubles – replace what you don't want to test

Technique | Replaces | Note |
|---|---|---|
Own local class | Any dependency behind an interface | Simplest; |
CL_ABAP_TESTDOUBLE | Global interfaces and global classes that are not FINAL | Framework creates and configures the double ( |
CL_OSQL_TEST_ENVIRONMENT | Database tables (and views) read in ABAP SQL | Redirects the SQL to test data you insert |
CL_CDS_TEST_ENVIRONMENT | The sources of the CDS view under test | Tests CDS logic with your own data |
CL_BOTD_TXBUFDBL_BO_TEST_ENV | A RAP BO your code uses via EML | Transactional buffer double: EML works on test instances you insert |
CL_BOTD_MOCKEMLAPI_BO_TEST_ENV | A RAP BO your code uses via EML | Mocks EML calls: you configure the output for a given input and can verify the calls |
| Code blocks in legacy code | Last resort when code can't be refactored |
Injecting test doubles
A double is useless until the code under test uses it. Four ways to get it in – constructor injection is the default, the others fit special cases.
Technique | How | When |
|---|---|---|
Constructor injection | Dependency is a constructor parameter (code above) | Default; the dependency is visible in the signature |
Setter injection | The class creates the real dependency; a setter | Optional or rarely changed dependencies |
Parameter injection | The method that needs the dependency gets it as a parameter | Only one method needs it |
Back-door injection | The test class is a | No public way to inject; keep the production API unchanged |
|
- Injector / factory: production code gets its dependency from a factory class (
zcl_demo_rates_factory=>get( )). A test-only injector class – a friend of the factory,FOR TESTING– stores a double in the factory, which then hands it out instead of the real object. - Clean ABAP: use LOCAL FRIENDS to reach a dependency-inverting constructor, but don't misuse it to invade the tested code; test the public methods, not the private internals.
CL_ABAP_TESTDOUBLE – let the framework build the double
|
configure_call( )followed by one call of the double = "when called with these arguments, return this".and_expect( )plusverify_expectations( )also check how often it was called.- Limits: global interfaces and global, non-final classes only – not local classes or interfaces, and not classes that are FINAL, FOR TESTING, CREATE PRIVATE or have a constructor with mandatory parameters. Then write your own double class.
Replacing the database: CL_OSQL_TEST_ENVIRONMENT
|
- Create the environment once in
class_setup, clear and fill it insetup, destroy it inclass_teardown. The real table is never read or changed. CL_CDS_TEST_ENVIRONMENT=>create( i_for_entity = 'ZI_DEMO_FLIGHT' )works the same way for a CDS view under test: it doubles the view's sources so you can check its joins, filters and calculations.- SFLIGHT keeps the example close to the rest of the page; in ABAP Cloud you would use released or own tables (e.g. the
/DMO/flight model).
Test seams – a workaround for legacy code
|
- In a test run the injected code replaces the seam's block; in normal runs the original block runs.
TEST-INJECTIONis only allowed in test classes of the same program or class pool. - Clean ABAP: use test seams only as a temporary workaround – refactor towards an interface and injection. Availability in ABAP Cloud: check your release.
RAP business objects
- Code that uses a RAP BO through EML is tested with the RAP BO test doubles (
CL_BOTD_TXBUFDBL_BO_TEST_ENVtransactional buffer double,CL_BOTD_MOCKEMLAPI_BO_TEST_ENVmock EML API); the BO's own handlers are tested with EML in the test class. Code: RAP › 12 · Extensibility & Testing.
Part 12 – OO in ABAP Cloud and S/4HANA
ABAP Cloud is SAP's development model for upgrade-stable, cloud-ready code: the only model in the SAP Business AI Platform, ABAP environment and S/4HANA Cloud Public Edition, and the recommended one (tier 1 of the clean core) in S/4HANA on-premise and Private Cloud. The OO language does not change – classes, interfaces, exceptions, events and ABAP Unit work exactly as on this page. What changes is which objects you may use, and how code is run and shown. Clean core background: Clean Core › 01 Clean Core.

ABAP language versions
Language version | Where | What it allows |
|---|---|---|
Standard ABAP | Classic on-premise code | The whole language, every repository object |
ABAP for Cloud Development | SAP Business AI Platform, ABAP environment, S/4HANA Cloud, tier 1 software components on-premise | Restricted syntax (no SAP GUI, dynpro or list statements) and released APIs only |
ABAP for Key Users | Key-user tools (custom fields and logic) | A further restricted subset |
- The version is a property of each object (ADT: Properties → General → ABAP Language Version), usually inherited from its software component. The syntax check enforces it – a forbidden statement is a syntax error, not a warning.
- Classic code can be checked for cloud readiness with the ATC check variant
ABAP_CLOUD_READINESS.
Released APIs: release contracts and API state
In ABAP Cloud you may only use SAP objects that SAP has released – classes, interfaces, CDS views, data elements, BAdIs. A release is a promise that the object stays stable across upgrades.
- API state – ADT: open the object → Properties → API State. It shows whether the object is released, for which release contract, and – for deprecated objects – the successor. Released objects are also listed under Released Objects in the Project Explorer.
- Release contracts: C1 – use system-internally, i.e. in your ABAP Cloud code: the contract that matters for classes and CDS views. C0 – stable extension points (extend an object). C2 – use as a remote API. Further contracts exist for special cases.
- Your own classes are used freely inside their software component; to offer them to other components you release them yourself (API state, C1).
- Dynamic access counts too:
CREATE OBJECT … TYPE (name), dynamic method calls and dynamic ABAP SQL compile, but fail at runtime if the object is not released. - Finding replacements: the successor in the API state, SAP's Cloudification Repository (lists unreleased objects with their successors), released CDS views such as
I_Productinstead of tables, XCO instead of many function modules.
What is not available – and what replaces it
Classic technique | ABAP Cloud replacement | More on |
|---|---|---|
SAP GUI: SE24, SE80, SE91, SE93 | ADT in Eclipse (class and message class editors) | Page 01 |
Executable programs ( | Class with | Page 01 Part 3 |
Dynpro, | Fiori elements app on a RAP service | Page 04; RAP section |
Object Services (persistence and transaction service) | RAP business object: CDS + behaviour pool + EML | Part 14; RAP |
OTR texts in exception classes | Message classes ( | Part 4 |
Unreleased SAP classes, function modules, tables (e.g. | Released classes and CDS views (C1), XCO library | Below |
OO transactions (SE93) | Fiori app (RAP/OData) or application job | Part 13 |
Shared objects, test seams | Check your release before relying on them | Parts 8, 11 |
RAP behaviour pool = ABAP Objects
The behaviour of a RAP business object is implemented in a behaviour pool: an ordinary global class with special additions. The real code is in local classes in its Local Types include (CCIMP) – a direct use of what pages 01–02 teach. Below is the skeleton of the Sales Order Approval app's pool; full anatomy and all method signatures: RAP › 04 · Behavior Definition & Behavior Pool.
|
Class | OO rules it uses |
|---|---|
Behaviour pool |
|
Handler | Local class INHERITING FROM |
Saver | Local class INHERITING FROM |
- You never create handler or saver objects: the RAP runtime instantiates and calls them – inversion of control, like an event handler.
- Inside handlers: EML (
READ ENTITIES … IN LOCAL MODE,MODIFY ENTITIES) instead of direct table access, errors viafailed/reported(Part 4), and noCOMMIT WORKorROLLBACK WORK– the RAP transaction decides when to save.
XCO – released utility classes
The XCO library (Extension Components) is a set of released classes with a fluent OO API. In ABAP Cloud it replaces many function modules and system fields.
|
- Further XCO areas:
xco_cp_json(JSON),xco_cp_xlsx(Excel files, page 04),xco_cp_abap_repository(read repository objects such as classes) and more – see SAP Help "XCO library". - Other released helpers:
CL_ABAP_CONTEXT_INFO(user, date, time zone),CL_SYSTEM_UUID,CL_ABAP_RANDOM_INT.
Part 13 – OO transactions (SE93)
A transaction code can start a method of a class directly instead of a report or dialog program.
- SE93 → enter the new code → Create → short text → start object "Method of a class (OO transaction)".
- Enter class and method. For a local class tick "Local in program" and enter the program name.
- Leave "OO transaction model" unticked to call a normal method. Ticked, the transaction runs under the transaction service of Object Services (Part 14, legacy).
- For an instance method the system creates the object first, so the constructor must not have mandatory parameters. Save and assign a package.
- Modern alternative for users: a Fiori app (RAP/OData); for background logic: a report or application job that calls the class. ABAP Cloud has no SAP GUI transactions (Part 12).
Part 14 – Legacy: persistence service and transaction service
Legacy – know it for interviews. Object Services (persistence and transaction service) map objects to database tables without SQL. They still run in classic systems but are not available in ABAP Cloud and are not used in new S/4HANA development: RAP business objects replace them – CDS for the data model, EML (MODIFY ENTITIES, COMMIT ENTITIES) for changes. See RAP › 08 · EML.
Persistence service
- Normally an object lives only while the program runs (the garbage collector frees it when no reference points to it, at the latest when the internal session ends). A persistent object keeps its state in the database; a transient object exists only in memory.
- Persistence class
ZCL_<name>: always global (SE24), alwaysCREATE PROTECTED, implementsIF_OS_STATE. Creating it generates two more classes:- Base agent
ZCB_<name>: abstract, friend of the persistence class, holds the generated methods. - Agent (actor)
ZCA_<name>: subclass of the base agent,CREATE PRIVATE, a singleton reached through its public static READ-ONLY attributeAGENT(filled by its static constructor on first access).
- Base agent
- Mapping (Goto → Persistence Representation): map every table field; fields become attributes with generated
GET_…methods (all) andSET_…methods (non-key fields).
Mapping type | Object identity | Key generated methods |
|---|---|---|
Business key | The table's primary key |
|
Instance GUID | First field GUID with data element |
|
Business key + GUID | Both: GUID as key, business key unique | Combination of the two |
- GUID mapping: every field except GUID becomes an attribute, and
GET_…andSET_…methods are generated for all of them (the rule "SET_ only for non-key fields" is the business-key case). - Delete by GUID:
IF_OS_FACTORY~DELETE_PERSISTENTexpects anIF_OS_STATEreference. An interface cannot be instantiated, so read the object withGET_PERSISTENT_BY_OID( guid ), down cast it (?=/CAST) to the persistence class (which implements IF_OS_STATE) and pass that object.
|
Transaction service
Groups changes to persistent objects into one OO transaction that is committed or rolled back as a whole. Classes: CL_OS_SYSTEM, IF_OS_TRANSACTION_MANAGER, IF_OS_TRANSACTION.
|
- In a normal report call
CL_OS_SYSTEM=>INIT_AND_SET_MODESonce first. In "OO transaction model" mode (SE93, Part 13) you must not code COMMIT WORK yourself –end( )commits. Plain COMMIT WORK applies in compatibility mode. - Passing selection-screen values to the transaction method through ABAP memory (
EXPORT … TO MEMORY) is also legacy; pass parameters to a method instead.
Part 15 – Interview questions
What are the three exception categories and how do you choose?
All inherit from CX_ROOT. CX_STATIC_CHECK: must be declared in RAISING, checked at compile time – for errors every caller must expect (most custom exceptions). CX_DYNAMIC_CHECK: checked at runtime – for errors the caller can avoid by checking first (CX_SY_ZERODIVIDE). CX_NO_CHECK: implicitly declared – for errors that can't sensibly be handled locally (resource shortage).
When does the CLEANUP block run? Can a TRY have CATCH and CLEANUP together?
Yes – any number of CATCH blocks plus one CLEANUP after them. CLEANUP runs only when an exception from this TRY is not caught here but by an outer handler; it must end normally through ENDTRY. If the exception is caught locally, or nobody catches it (short dump), CLEANUP does not run. ABAP has no FINALLY.
What does RAISING do, and what happens if an exception is not declared?
RAISING lets the exception propagate to the caller, who handles it. If a STATIC or DYNAMIC check exception leaves a method without being declared, the runtime raises CX_SY_NO_HANDLER with the original exception in PREVIOUS; unhandled, that dumps.
Classic exceptions vs class-based exceptions?
Classic: EXCEPTIONS in the signature, RAISE name or MESSAGE … RAISING, caller checks SY-SUBRC; no object, no text, no propagation through several levels. Class-based: exception objects with texts and PREVIOUS chaining, propagate automatically, handled with TRY/CATCH. One method can't mix both; new code uses class-based exceptions.
How do you create a custom exception class with a message from a message class?
Create ZCX_… in SE24/ADT inheriting from CX_STATIC_CHECK (usually), tick "With message class" so it implements IF_T100_MESSAGE (or IF_T100_DYN_MSG), define exception ID constants (MSGID, MSGNO, ATTR1–4) and attributes for the placeholders. Raise with RAISE EXCEPTION TYPE zcx_… EXPORTING textid = … or, with IF_T100_DYN_MSG, RAISE EXCEPTION TYPE zcx_… MESSAGE e001(zmsg) WITH …. OTR texts are legacy.
What is the difference between RESUME and RETRY?
RESUME continues in the raising method right after a RAISE RESUMABLE EXCEPTION; it needs CATCH BEFORE UNWIND and RESUMABLE in every RAISING clause on the way. RETRY restarts the whole TRY block from the beginning – fix the cause first or you loop forever.
Explain events in ABAP – what are the steps?
Declare the event with EVENTS/CLASS-EVENTS (EXPORTING parameters by value), declare a handler method FOR EVENT … OF class, register it with SET HANDLER before the event is raised, raise it with RAISE EVENT inside a method. Handlers are never called directly; unregistered handlers don't run. It is the observer pattern; ALV events (double_click, hotspot_click) work the same way.
Instance event vs static event – and what is SENDER?
Instance events (EVENTS) are raised only in instance methods and registered per sender (FOR lo_obj or FOR ALL INSTANCES). Static events (CLASS-EVENTS) can be raised in any method of the class and are registered without FOR. SENDER is the implicit parameter of instance events – a reference to the object that raised it. ACTIVATION abap_false deregisters a handler.
What is RTTS? How do you create an internal table for a table name known only at runtime?
RTTS = RTTI (describe types: CL_ABAP_TYPEDESCR=>describe_by_name/data/object_ref) + RTTC (create types: CL_ABAP_STRUCTDESCR=>get, CL_ABAP_TABLEDESCR=>create). Get the structure description, build the table type, CREATE DATA lr TYPE HANDLE lo_type, ASSIGN lr->* to a field symbol, SELECT FROM (name). Shortcut: CREATE DATA lr TYPE STANDARD TABLE OF (name). Always validate the name (allow-list, CL_ABAP_DYN_PRG) and check authorization – otherwise users can read any table.
How do you implement a singleton? Give a factory example from SAP.
Class FINAL CREATE PRIVATE, a private static attribute holding the instance, and a public static get_instance method that creates it on first call and always returns the same reference. Factory example: CL_SALV_TABLE=>FACTORY creates the ALV object for you; your own factories return an interface reference and choose the implementing class inside.
How do you write an ABAP Unit test, and how do you isolate dependencies?
Local class FOR TESTING with RISK LEVEL and DURATION, test methods FOR TESTING (concrete, no parameters), fixtures setup/teardown and class_setup/class_teardown, checks with CL_ABAP_UNIT_ASSERT. Isolate dependencies by injecting interfaces (constructor injection) and passing a test double – own class, CL_ABAP_TESTDOUBLE, CL_OSQL_TEST_ENVIRONMENT for tables, CL_CDS_TEST_ENVIRONMENT for CDS. Run with Ctrl+Shift+F10.
What is the persistence service, and what replaces it in S/4HANA?
Object Services map a persistence class (CREATE PROTECTED, IF_OS_STATE) to a table by business key, GUID or both; the generated singleton agent class (ZCA_…=>AGENT) offers CREATE/GET/DELETE_PERSISTENT, and the transaction service (CL_OS_SYSTEM) bundles changes. It is legacy and not available in ABAP Cloud; new development uses RAP business objects with CDS and EML.
What changes for object-oriented development in ABAP Cloud?
The OO language stays the same; the rules around it change. Objects use the language version ABAP for Cloud Development, so only released SAP APIs can be used (also dynamically) and SAP GUI techniques are gone: no SE24 (ADT instead), no reports or WRITE lists (IF_OO_ADT_CLASSRUN, application jobs), no CL_GUI_ALV_GRID or SALV (Fiori elements on RAP), no Object Services (RAP BOs), no OTR texts (message classes). XCO and released CDS views replace many function modules and tables.
What is a released API and what does the C1 contract mean?
A released API is an SAP object that SAP promises to keep stable across upgrades. ADT shows it on the API State tab: released or not, for which release contract, and the successor if it is deprecated. C1 means "use system-internally" – the object may be used in ABAP Cloud code; C0 covers extension points and C2 remote APIs. Classic code is checked with the ATC variant ABAP_CLOUD_READINESS.
What is a RAP behaviour pool, and which OO concepts does it use?
A global class ABSTRACT FINAL … FOR BEHAVIOR OF the BO, normally empty. The logic sits in local classes: handler classes inheriting from CL_ABAP_BEHAVIOR_HANDLER with methods FOR MODIFY / READ / VALIDATE / DETERMINE, and a saver class inheriting from CL_ABAP_BEHAVIOR_SAVER that redefines the save-sequence methods. The RAP runtime creates and calls them; errors go into failed and reported, not into exceptions, and handlers never COMMIT.
How do you get a test double into the code under test, and when is CL_ABAP_TESTDOUBLE not enough?
Constructor injection by default; setter or parameter injection for optional or single-use dependencies; back-door injection through LOCAL FRIENDS; or a factory with a test injector. Databases are replaced with CL_OSQL_TEST_ENVIRONMENT, CDS sources with CL_CDS_TEST_ENVIRONMENT, RAP BOs with the CL_BOTD_* environments, legacy blocks with test seams. CL_ABAP_TESTDOUBLE only doubles global interfaces and global classes that are not FINAL, FOR TESTING or CREATE PRIVATE and have no mandatory constructor parameters. And: without RISK LEVEL a test class counts as CRITICAL.
Exception, ASSERT or RAISE SHORTDUMP – which one when?
An exception (RAISE EXCEPTION NEW) for errors that can happen and that a caller may handle; chain the cause with previous. ASSERT for conditions that can only be false through a bug (ASSERTION_FAILED). RAISE SHORTDUMP (7.53) for unrecoverable states: it cannot be caught and writes the exception class and its text into the short dump. Clean ABAP: dump only for totally unrecoverable situations.
🏠 Start Here · ◀ 02 · Inheritance & Interfaces · 04 · ALV Reporting ▶ · Sections: CORE ABAP | OOPS ABAP | ABAP on HANA | Clean Core | RAP | ABAP Points | SAP Fiori | SAPUI5 | Mobile Development (MDK) | BTP Foundations | BTP Development | CAP | SAP Build | ABAP on BTP | Integration Suite | SAP Business AI | SAP BASIS | Security | SAP SDLC
Functional: FICO ABAP | TRM ABAP | VIM | SAP BIS | SD ABAP | MM ABAP | PP ABAP | QM ABAP | PM ABAP | PS ABAP | EWM | TM ABAP | GTM ABAP | EHS ABAP | HR ABAP | BW | SAP Datasphere | SAP Business Data Cloud | SAP MDG | SAP Analytics Cloud | SAP Ariba | SAP CX | SAP IBP