ABAP class-based exceptions: Preserve the cause in the error path
A manufacturing purchasing extension cannot calculate a unit value for one input and needs a controlled failure that the caller can explain.
START HERE · NO PRIOR TOPIC KNOWLEDGE NEEDED
What it is. Why it matters.
An exception is a program’s way of reporting that an operation could not finish normally. ABAP class-based exceptions carry information that a caller can catch and handle.
Completely new to SAP?
Manufacturers use SAP to connect work such as buying components, recording inventory, planning production, shipping equipment and accounting for costs. SAP S/4HANA is an enterprise resource planning system: it connects these activities through shared business data.
ABAP is SAP’s programming language for business applications. A program reads data, applies rules and produces a result. Start with the objects involved before investigating code.
A transaction code, or t-code, is a shortcut to a task in classic SAP GUI. Fiori apps provide another way to work. Names and screens depend on the product and release; you do not need a live system to learn the concepts in this guide.

Scope and source-review notes
Scope and evidence
Source review by FAST SAP SOLUTIONS® editorial. This badge describes our editorial review; it does not represent SAP certification or independent endorsement.
ABAP class-based exception control flow and exception chaining; application-specific messaging, logging and transaction policies must match the target release.
Primary documentation reviewed on 14 November 2026 using readable full text and official indexed excerpts. Documentation review only; authored examples were not compiled or executed in an SAP system.
A MANUFACTURING EXAMPLE
Explain a failed component-price calculation
An exception needs an outcome
Read the example values
- Operation
- Read order 1001
- Problem
- Order not found
- Caught exception
- Missing document
- Caller outcome
- Explain the missing order
Words you’ll meet in this guide
- Program
- A set of instructions executed by a computer.
- Class
- A reusable unit that groups data with operations called methods.
- Database
- Organized information kept beyond one program execution.
- Internal table
- A list of rows held temporarily in an ABAP program’s memory.
- Key
- One or more fields used to identify or find a record.
- ABAP
- SAP’s programming language for business applications.
- API
- A defined interface through which programs exchange data or request actions.
- BAPI
- Business Application Programming Interface: an SAP interface for a business operation.
Preview the practical steps
SEE THE CONNECTION
See it in a simple example.
A small example to make the idea concrete.
Explain a failed component-price calculation
A manufacturing purchasing extension cannot calculate a unit value for one input and needs a controlled failure that the caller can explain.
An exception needs both a cause and an intentional outcome
An ABAP class-based exception is an object describing an exceptional condition.
Audience and language scope
This guide assumes basic ABAP Objects knowledge: methods, class references and declared interfaces.
How control moves through TRY and CATCH
Statements in the TRY block execute in order.
Explain a failed component-price calculation
A manufacturing purchasing extension cannot calculate a unit value for one input and needs a controlled failure that the caller can explain.
Trace the invalid input, exception contract and caller handling before hiding the failure behind a default number.
| Reader | Business question | Evidence to carry forward |
|---|---|---|
| SAP developers and application teams supporting manufacturers | Explain a failed component-price calculation | Trace the invalid input, exception contract and caller handling before hiding the failure behind a default number. |
01 An exception needs both a cause and an intentional outcome
An ABAP class-based exception is an object describing an exceptional condition. Catching it transfers control to a matching handler; it does not make the failed operation successful. A useful handler either recovers with a valid alternative, rejects the business operation clearly, or translates the failure while preserving the original cause for controlled diagnosis. [1]
The common defect is a broad CATCH that logs little and then continues with initial or stale data. Another is translating every technical failure into the same customer message while discarding the exception object. This tutorial builds a small error boundary around a calculation so that a caller can understand what failed, preserve the cause and avoid returning a misleading amount.
02 Audience and language scope
This guide assumes basic ABAP Objects knowledge: methods, class references and declared interfaces. TRY, CATCH, RAISING and class-based exception hierarchies are established ABAP concepts across classic ABAP and modern development. Specific available exception classes, message integration and application logging APIs remain release- and application-dependent.
The sample uses local customer classes and standard arithmetic exception handling. It is illustrative code for a compatible development environment, not a compiled customer-system artifact. A production exception class would normally define meaningful text identifiers or message integration and carefully chosen contextual attributes. Check syntax and permitted objects in your ABAP language version before adapting it.
03 How control moves through TRY and CATCH
Statements in the TRY block execute in order. When an exception occurs, normal processing of the remaining statements in that block stops. The runtime searches matching handlers, including handlers for a superclass of the raised exception, and proceeds through the applicable enclosing contexts. After a handler finishes normally, processing continues after ENDTRY rather than resuming the failed statement. [1]
List specific handlers before general handlers. Catching a superclass covers its subclasses, so a general CX_ROOT handler belongs after more specific cases. Use INTO to obtain the exception reference when diagnostic context is needed. A variable assignment after the failed statement has not occurred merely because the handler eventually returns control to the caller. [1]
04 Choose an exception category as part of the interface
ABAP's exception hierarchy has CX_ROOT above the category classes CX_STATIC_CHECK, CX_DYNAMIC_CHECK and CX_NO_CHECK. These categories influence interface and checking rules. A checked business exception often makes an expected failure path visible to callers through a RAISING declaration. An unchecked category is not a license to ignore a failed operation. [2]
Choose the public contract from what a caller can do. If “document not found” is an ordinary search outcome, an explicit optional result may be clearer than exceptional control flow. If a posting service cannot satisfy a required precondition, a declared exception may communicate the failed operation more reliably. Do not create one exception per database symptom when callers need a stable business-level contract.
05 Worked case: a unit-price calculation with zero quantity
Imagine an import row containing document R100, amount 120.00 EUR and quantity 6 PC. The expected unit price is 20.00 EUR/PC. Row R101 contains amount 120.00 EUR and quantity zero. Division cannot yield a meaningful unit price. Returning zero would imply a valid free unit, and retaining 20.00 from R100 would assign another row's result to R101.
The calculation boundary should report a price-calculation failure and retain the original arithmetic cause. The caller can then reject R101 and display a concise message tied to its row reference. The internal exception chain explains the technical failure without exposing sensitive source payloads to every end user. This separates business recovery from low-level diagnosis.
| Row | Amount / quantity | Expected outcome |
|---|---|---|
| R100 | 120.00 EUR / 6 PC | 20.00 EUR/PC |
| R101 | 120.00 EUR / 0 PC | Rejected; no price result |
| R102 | 0.00 EUR / 4 PC | 0.00 EUR/PC if allowed |
| R103 | 120.00 EUR / -6 PC | Business rule must decide negative quantity |
06 Preserve the exception using PREVIOUS
When translating an exception, pass the caught object as PREVIOUS to the new exception's constructor. This preserves a chain: the outward exception expresses the service's contract, while the earlier object explains its cause. Do not reduce the chain to a text string unless the receiving boundary genuinely cannot carry exception objects. [3]
The local example inherits the constructor and uses a standard arithmetic failure as its previous cause. It deliberately leaves out application-specific logging and user-message mapping. The caller must treat an exception as failure and must not consume the result. A real service can add a document reference and text identifier while keeping confidential amounts and payload values out of public error details.
CLASS lcx_price_failure DEFINITION
INHERITING FROM cx_static_check.
ENDCLASS.
CLASS lcx_price_failure IMPLEMENTATION.
ENDCLASS.
CLASS lcl_price DEFINITION.
PUBLIC SECTION.
CLASS-METHODS calculate
IMPORTING amount TYPE decfloat34
quantity TYPE decfloat34
RETURNING VALUE(result) TYPE decfloat34
RAISING lcx_price_failure.
ENDCLASS.
CLASS lcl_price IMPLEMENTATION.
METHOD calculate.
TRY.
result = amount / quantity.
CATCH cx_sy_zerodivide INTO DATA(cause).
RAISE EXCEPTION TYPE lcx_price_failure
EXPORTING previous = cause.
ENDTRY.
ENDMETHOD.
ENDCLASS.07 Put recovery at the layer with enough information
The calculation method knows that it could not compute a price. It usually does not know whether the entire import should stop, the row should be quarantined or an authorized user should supply missing quantity. Those decisions belong to the caller that owns the import workflow. Preserve this separation so the method remains reusable.
At the workflow boundary, record a failed-row state and avoid downstream posting for R101. If a batch policy allows independent rows, continue only with rows whose results are valid. If the entire import must be atomic, reject the batch according to the transaction owner. Do not let an inner CATCH quietly choose a transaction policy by swallowing one exception and allowing later writes.
08 Do not confuse CLEANUP with a finally block
ABAP CLEANUP has a specific exception-propagation role. It executes when an exception leaves that TRY context without being handled there and is handled in an enclosing context or propagated to a caller. It is not a universal block that runs after every successful execution or every local CATCH. [1]
Use it to restore a context that would otherwise be left inconsistent during propagation, following the documented restrictions. If a resource must be released on both normal and exceptional paths, design both paths explicitly or use an appropriate supported lifetime pattern. A mistaken assumption that CLEANUP always executes can leave a lock or temporary state behind even though the normal calculation succeeded. [1]
09 Troubleshoot exception handling from the symptom
Start from the actual failed operation and reconstruct the call chain. A short dump can mean no applicable handler existed, an interface propagation rule was violated, or another failure occurred in error handling itself. A successful-looking UI can instead mean that a handler hid the failure. Both require inspecting the exception boundary, not merely adding another broad catch.
| Symptom | Question | Next observation |
|---|---|---|
| Method returns success after failure | Was the exception swallowed? | Inspect handler and success assignment |
| Same amount appears on next row | Was a previous result reused? | Trace result initialization and failure branch |
| Only generic message remains | Was PREVIOUS discarded? | Inspect translated exception construction |
| Specific recovery never runs | Does a general handler catch first? | Review hierarchy and handler order |
| Cleanup missing after success | Was CLEANUP treated as unconditional? | Trace normal and propagation paths |
| Dump during error handling | Did logging or cleanup raise again? | Inspect the new exception and original chain |
10 Verification: test the sequence, not only isolated calls
Use a positive fixture with 120 divided by 6 and assert the returned 20. For the negative fixture, call with zero quantity and assert that the public exception is raised. Inspect that PREVIOUS refers to the original arithmetic exception where the design promises translation. Confirm that no success status or usable unit price is returned for the rejected row.
Then run R100 followed by R101 in the same workflow. The second row must not inherit the first result. Add a case with zero amount and positive quantity to distinguish a valid zero from failure. Negative quantities require an explicit business rule; a mathematically valid result does not prove that the business operation is permitted. These are proposed checks until executed in the target development environment.
11 Messages, diagnosis and transaction state
Expose a useful user message such as “Unit price cannot be calculated for row R101 because quantity is zero,” if that information is appropriate for the audience. Keep deeper technical details in the application's approved diagnostic channel. An exception's GET_TEXT output can help support, but it is not automatically suitable as a public API message.
Record transaction state separately from exception state. Raising or catching a class-based exception does not by itself specify every database commit or external effect. If earlier work might already have been persisted or a remote request was sent, the workflow must reconcile that outcome. Avoid reporting a universal rollback simply because a later method raised an exception. The transaction-owning layer must define and verify the boundary.
12 Questions to settle in code review
Should I always catch CX_ROOT? Use a broad handler only at a deliberate boundary that can produce a valid failure response and preserve diagnosis. A broad catch inside a low-level helper can hide defects the caller needs to see.
Should I create a new exception class for every failure? Create a stable contract that lets callers take appropriate action. Preserve technical causes through chaining rather than multiplying public exception types without useful recovery differences.
Can a handler retry? Only when the operation and state make retry valid. Correcting input is different from blindly repeating an uncertain business write.
What proves the fix? A valid-result case, a declared-failure case, a checked cause chain and a repeated-row case together show more than the absence of a dump. Review the related stale-work-area and BAPI transaction lessons when error handling crosses those boundaries.
Related services and next steps
Primary sources
Found this useful?
Share this guide with your network, or leave a like.
Your like is saved in this browser.