COMP273

Test-Driven and Bulletproof ABAP Development

Stefan Bresch, SAP AG NW F ABAP Thomas Ritter, SAP AG NW F ABAP

Disclaimer

This presentation outlines our general product direction and should not be relied on in making a purchase decision. This presentation is not subject to your license agreement or any other agreement with SAP. SAP has no obligation to pursue any course of business outlined in this presentation or to develop or release any functionality mentioned in this presentation. This presentation and SAP's strategy and possible future developments are subject to change and may be changed by SAP at any time for any reason without notice. This document is provided without a warranty of any kind, either express or implied, including but not limited to, the implied warranties of merchantability, fitness for a particular purpose, or non-infringement. SAP assumes no responsibility for errors or omissions in this document, except if such damages were caused by SAP intentionally or grossly negligent.

© SAP 2008 / SAP TechEd 08 / <COMP273> Page 2

Agenda (Warm Up)

“Everything that can possibly go wrong will go wrong” (Murphy’s Law)

© SAP 2008 / SAP TechEd 08 / <COMP273> Page 3

1. Code Inspector 2.1. Test Driven Development with ABAP Unit 2. ABAP Unit Browser 3.Agenda 1. Static checks 1.2. Dynamic tests 2. Exceptions 3.2.3. Robust code 3.1. Coverage Analyzer 3. Asserts © SAP 2008 / SAP TechEd 08 / <COMP273> Page 4 .

The default tests also contain the Extended Program Check (SLIN).Static Checks: Code Inspection From The ABAP Editor ABAP Editor Code inspection from SE38: The Code Inspector executes a default test set for a chosen program. Code inspector is available with WEB AS 6.10 for R/3 >= 46C a transport is available -> note 543359 © SAP 2008 / SAP TechEd 08 / <COMP273> Page 5 .

DEMO © SAP 2008 / SAP TechEd 08 / <COMP273> Page 6 .

They start all with ZTSTECHED* © SAP 2008 / SAP TechEd 08 / <COMP273> Page 7 .Static Checks: Code Inspector – Exercise Exercise 1: Use the code inspector to run the extended program check or syntax check for all our test programs.

1.1. Asserts © SAP 2008 / SAP TechEd 08 / <COMP273> Page 8 . Code Inspector 2. Test Driven Development with ABAP Unit 2.2.Agenda 1. Coverage Analyzer 3. Static tests 1.2. Robust code 3.1.3. Exceptions 3. ABAP Unit Browser 3. Dynamic tests 2.

there are xUnit frameworks for nearly every programming language. Static checks cannot test if a function. function module) of a program under well-defined test conditions and to inspect and verify the behavior. A developer runs his unit tests every time he changes his code (regression tests) The first popular testframework was SUnit for Smalltalk developed by Kent Beck. form or method “works as designed”. Static checks cannot detect problems that occur only at runtime.Introduction Unit Tests I What are Unit Tests good for? There is a gap between static and integration tests. Integration tests are too expensive to use for detecting errors on unit level. Now. Unit tests allow you to execute a single modularization unit (method. © SAP 2008 / SAP TechEd 08 / <COMP273> Page 9 . form.

© SAP 2008 / SAP TechEd 08 / <COMP273> Page 10 . Thereby defects are detected very early in the development process and can be fixed easily. Extensive unit tests allow developers to reach this goal since they make refactorings possible which in return improves maintainability. it therefore serves as an excellent technical documentation. Software grows over time therefore it is important to keep the code clean and agile.Introduction Unit Tests II Benefits A developer runs his unit tests every time he changes his code (regression tests). Often unit tests serve as great examples how a certain piece of code should work. A well written unit tests tells the developer exactly what is wrong and where the error is located. Therefore developers use the debugger less often for locating errors. Unit tests specify exactly how a piece of software should behave in a given scenario.

2. Tightly integrated into the programming language Production code and unit test code are bundled and transported together Test code cannot be executed in a production system. © SAP 2008 / SAP TechEd 08 / <COMP273> Page 11 . Its most remarkable features are: 1. ABAP Unit is available with NetWeaver 04. 3.Introduction ABAP Unit I ABAP Unit is the official xUnit testing framework for ABAP.

METHODS: test_create_flight FOR TESTING. PRIVATE SECTION.Introduction ABAP Unit II ABAP Unit tests are usually implemented as local ABAP Objects classes in the main program that contains the tested modularization units. Example test class definition: CLASS ltcl_flight DEFINITION FOR TESTING RISK LEVEL HARMLESS DURATION SHORT. ENDCLASS. © SAP 2008 / SAP TechEd 08 / <COMP273> Page 12 .

METHODS: test_create_flight FOR TESTING. Define class as test class CLASS ltcl_flight DEFINITION FOR TESTING RISK LEVEL HARMLESS DURATION SHORT. PRIVATE SECTION. Define method as test method © SAP 2008 / SAP TechEd 08 / <COMP273> Page 13 .ABAP Unit – For testing For testing: used to mark classes as test classes and methods as test methods. ENDCLASS.

METHODS: test_create_flight FOR TESTING. © SAP 2008 / SAP TechEd 08 / <COMP273> Page 14 . harmless. PRIVATE SECTION. Define risk level CLASS ltcl_flight DEFINITION FOR TESTING RISK LEVEL HARMLESS DURATION SHORT.ABAP Unit – Risk Level Risk level: used to define the risk level of the test class dangerous. critical. ENDCLASS.

PRIVATE SECTION.ABAP Unit – Duration Duration: used to define the expected runtime duration of all test methods short. long. medium. ENDCLASS. Define duration CLASS ltcl_flight DEFINITION FOR TESTING RISK LEVEL HARMLESS DURATION SHORT. © SAP 2008 / SAP TechEd 08 / <COMP273> Page 15 . METHODS: test_create_flight FOR TESTING.

ABAP Unit – System Configuration Profile parameter: abap/test_generation Transaction: SAUNIT_CLIENT_SETUP © SAP 2008 / SAP TechEd 08 / <COMP273> Page 16 .

… Implement your own assert methods by using the method fail() all assert statements allow you to add a message via the parameter (msg) which will be displayed in the UI Example: METHOD test_create_flight. assert_equals(). cl_aunit_assert=>assert_bound( flight ). DATA: flight TYPE REF TO cl_flight.ABAP Unit – Assert Methods Assert methods: used to determine whether a test is successful or not the utility class cl_aunit_assert offers various methods e.g. assert_bound(). ENDMETHOD. CREATE OBJECT flight EXPORTING flight_id = ‘LX34’. © SAP 2008 / SAP TechEd 08 / <COMP273> Page 17 .

© SAP 2008 / SAP TechEd 08 / <COMP273> Page 18 .ABAP Unit – Execute Tests Start unit tests from within the SE80 or execute a row of tests by using the code inspector.

ABAP Unit – Result Display © SAP 2008 / SAP TechEd 08 / <COMP273> Page 19 .

DEMO © SAP 2008 / SAP TechEd 08 / <COMP273> Page 20 .

What happens if you try to divide a number by zero? © SAP 2008 / SAP TechEd 08 / <COMP273> Page 21 . method divide_successful.Dynamic Tests: ABAP Unit – Exercise Exercise 2: Open the transaction SE80. class ltcl_calculator_tests implementation. endmethod. Use the static method CL_AUNIT_ASSERT=>ASSERT_EQUALS() for checking whether your test is successful or not. divides them and returns the result. The definition of the method looks like this: DIVIDE importing PARAM1 type i PARAM2 type i returning value(result) type i. Create a new report with the name ZTBEXERCISE2_<counter>. Write a test which checks the result of the DIVIDE method. endclass. Add a method DIVIDE to the local test class which receives two integer numbers as parameters. endclass. Get a feeling for the result display by causing your unit test to fail. Execute your test by using the menu “Program Test UnitTest” or use the keyboard shortcut: Shift + Strg + F10. Once you are finished try to add more tests. private section. methods: divide_successful for testing. Create your first local test class by using the following template: class ltcl_calculator_tests definition for testing duration short risk level harmless.

e.ABAP Unit – Test Creation Usual workflow when implementing a unit test: 1. 3. Implement the test in a method defined as for testing. Use the helper methods offered by the class cl_aunit_assert to check whether the code under test behaved in the way you expected it to behave. respectively). Write the necessary code to set up the environment in which the test runs (Fixtures are defined by a naming convention. Write the necessary code to tear down the environment. the methods setup. i. teardown and class_setup and class_teardown. It is important that tests are running in complete isolation. © SAP 2008 / SAP TechEd 08 / <COMP273> Page 22 . 2.

ABAP Unit – Test Execution ABAP Unit test execution flow: Setup for all tests class_setup() Setup for each test method Execute test method Teardown for each test method Teardown for all tests class_teardown() setup() test method teardown() © SAP 2008 / SAP TechEd 08 / <COMP273> Page 23 .

Define fixture methods © SAP 2008 / SAP TechEd 08 / <COMP273> Page 24 . class_teardown. METHODS: setup. PRIVATE SECTION.ABAP Unit – How to Define Fixture Methods Example test class: CLASS ltcl_flight DEFINITION FOR TESTING RISK LEVEL HARMLESS DURATION SHORT. ENDCLASS. CLASS-METHODS: class_setup. teardown.

Test Driven Development .Motivation Common problems with the “classic” unit testing approach Tests are written too late or not at all The production code is not testable Test coverage is low © SAP 2008 / SAP TechEd 08 / <COMP273> Page 25 .

Motivation One solution: Write the unit tests before the production code! © SAP 2008 / SAP TechEd 08 / <COMP273> Page 26 .Test Driven Development .

Test Driven Development .Process Write test Make it compile Test fails Make the test pass Refactor © SAP 2008 / SAP TechEd 08 / <COMP273> Page 27 .

DEMO © SAP 2008 / SAP TechEd 08 / <COMP273> Page 28 .

improve the design of your code by forcing you to design the API before implementing it.Test Driven Development . Helps you to design highly decoupled and thereby reusable code.Advantages Test Driven Development can help you to: improve the test coverage of your code by forcing you not to write any production code without a failing test. make your code more flexible © SAP 2008 / SAP TechEd 08 / <COMP273> Page 29 .

Create a new test class with the name LTCL_STACK_TESTS. What happens if you call POP on an empty stack? Write a test for the method SIZE. Create a new report ZTBEXERCISE3_<counter>. data: stack type ref to Implement the SETUP method which instantiates the stack attribute. Use the method ASSERT_EQUALS to make sure that the right results get returned. Suggestion: One developer writes the test the other developer writes the implementation which passes the test © SAP 2008 / SAP TechEd 08 / <COMP273> Page 30 . Add a private attribute to the test class ZCL_STACK.Dynamic Tests: ABAP Unit – Exercise Exercise 3: Open the transaction SE80. Write a test for the POP and PUSH method of the stack class.

If the code under test interacts with a method which has a non-deterministic behavior writing a test is not possible. Observability: You can only test what you can see If it’s not possible to query and check system states which get changed by the code under test then it is hard to test. Simplicity: The simpler. © SAP 2008 / SAP TechEd 08 / <COMP273> Page 31 . Availability: You can only test what you have access to Private methods cannot be tested easily however ABAP Objects friends feature offers a solution.ABAP Unit – Testability What affects testability? (James Bach) Controllability: You can only test what you can control. the easier it‘s too test Long methods are usually hard to test because they are responsible for handling too many different things.

method should ideally have only one purpose © SAP 2008 / SAP TechEd 08 / <COMP273> Page 32 . Short and precise methods. Every class. and UI coding object oriented programming.ABAP Unit – Testability Best practices for testability: clear separation between persistence. Use classes and interfaces to clearly define modules and to keep your code flexible simple clearly structured code. application.

Asserts © SAP 2008 / SAP TechEd 08 / <COMP273> Page 33 .Agenda 1. ABAP Unit Browser 3. Robust code 3. Dynamic tests 2. Exceptions 3. Code Inspector 2. Test Driven Development with ABAP Unit 2.3. Coverage Analyzer 3.1.1.2. Static tests 1.2.1.

10 © SAP 2008 / SAP TechEd 08 / <COMP273> Page 34 . find program parts that are executed very often and may benefit from code optimization Coverage Analyzer is available with WEB AS 6.Coverage Analyzer The Coverage Analyzer is a tool for monitoring the system-wide execution of ABAP programs. You can monitor which programs and even which modules of a program were covered by a test find program parts or complete programs which are never used and may be obsolete.

Coverage Analyzer SAP Easy Access /nscov /nscov Make sure that the coverage analyzer is running properly on your server before testing! © SAP 2008 / SAP TechEd 08 / <COMP273> Page 35 .

Coverage Analyzer – Global View (QM) © SAP 2008 / SAP TechEd 08 / <COMP273> Page 36 .

Coverage Analyzer – Detail View Check which modularization units of your programs were executed (covered) during a test. © SAP 2008 / SAP TechEd 08 / <COMP273> Page 37 .

DEMO © SAP 2008 / SAP TechEd 08 / <COMP273> Page 38 .

Agenda 1. Robust code 3. ABAP Unit Browser 3.1.3. Coverage Analyzer 3. Exceptions 3.2. Code Inspector 2. Test Driven Development with ABAP Unit 2. Dynamic tests 2. Asserts © SAP 2008 / SAP TechEd 08 / <COMP273> Page 39 . Static tests 1.1.1.2.

Introduction The ABAP Unit Browser is a tool for executing a set of unit tests. ABAP Unit Browser is available with SAP NetWeaver 7.1 © SAP 2008 / SAP TechEd 08 / <COMP273> Page 40 .ABAP Unit Browser . It allows to monitor the code coverage which unit tests produce.

ABAP Unit Browser – Create new favorite 1. Create a new favorite © SAP 2008 / SAP TechEd 08 / <COMP273> Page 41 .

ABAP Unit Browser – Add Test Classes 2. Add test classes to the favorite © SAP 2008 / SAP TechEd 08 / <COMP273> Page 42 .

ABAP Unit Browser – Configure Execution Options 3. Add coverage measurement © SAP 2008 / SAP TechEd 08 / <COMP273> Page 43 .

ABAP Unit Browser – Execute Favorite 4. Execute tests © SAP 2008 / SAP TechEd 08 / <COMP273> Page 44 .

ABAP Unit Browser – Analyze Results 5. Analyze results © SAP 2008 / SAP TechEd 08 / <COMP273> Page 45 .

Tick the checkbox “With Coverage Measurement” under extended measurement. Optional: Execute your tests by using the Code Inspector. Select “Favorite” in the dropdownlist and enter your username in the inputfield. © SAP 2008 / SAP TechEd 08 / <COMP273> Page 46 . Analyze the code coverage which your test methods produce. Add the reports created during exercise 2 and 3 to the favorite. Create a new favorite.ABAP Unit Browser – Exercise Exercise 4: Open the transaction SE80. Execute the unit tests. Select the ABAP Unit Browser (If the tool is not display in the workbench add it via the menu: Utilities Settings… Under tab “Workbench (General)” tick the checkbox “ABAP Unit Test Browser”).

Robust code 3.2. Test Driven Development with ABAP Unit 2.2.1.3. ABAP Unit Browser 3. Coverage Analyzer 3. Exceptions 3.1. Static tests 1.1.Agenda 1. Asserts © SAP 2008 / SAP TechEd 08 / <COMP273> Page 47 . Code Inspector 2. Dynamic tests 2.

© SAP 2008 / SAP TechEd 08 / <COMP273> Page 48 . system memory or disk storage). both for recoverable ( exceptions. When interacting with external resources (like the user. The ABAP language and infrastructure offers different ways for handling these kinds of errors.Motivation Software development and operation is intrinsically prone to errors in many ways Internal errors may arise from wrong implementations and improper usage of underlying services. messages) and non-recoverable errors ( assertions). errors can occur due to invalid input or unexpected resource limitations.

40 (SAP NetWeaver 04.0. mySAP ERP 2004. …) Classical Exceptions: prior to Release 4. CRM 4.0 © SAP 2008 / SAP TechEd 08 / <COMP273> Page 49 .Available Since… Exceptions Class-Based Exceptions: SAP_BASIS 610 (SAP WebAS 610) with T100-texts: SAP_BASIS 6.0 Catchable Runtime Errors: Release 4.

Principles of Exception Handling 1/2 Look at software as a (layered) collection of services In an error situation. a service has only limited knowledge about the (global) application context is probably not able to take corrective measures Best way to deal with error situation Signal what went wrong. passing along additional information Pass flow of control to a suitable handler which is able to react to that particular situation Requirements Separation of normal coding from error handler coding Selective definition of handlers for certain errors Automatic abort of routine. that cannot provide promised service (→ automatic propagation along call chain) © SAP 2008 / SAP TechEd 08 / <COMP273> Page 50 .

C++ © SAP 2008 / SAP TechEd 08 / <COMP273> Page 51 .Principles of Exception Handling 2/2 Exception as an object of an exception class Attributes can store additional information Refinement through inheritance Grouping by using inheritance Raising an exception Creation of exception object Propagation along call chain until suitable handler is found (change of control flow) If no handler is found: short dump Exceptions as part of signature of procedures Callers know about exceptions they have to deal with In principle comparable to Java.

CREATE OBJECT excp EXPORTING page = 'http://www. Exception raised by kernel (runtime exception) x = 1 / 0. "creates exception cx_sy_zerodivide Exception object contains additional information.Raising Class-Based Exceptions Raise exception with implicit object creation RAISE EXCEPTION TYPE cx_page_not_found EXPORTING page = 'http://www.sap. explaining text and position where exception occurred.com/shop/'. page.sap.com/shop/'. e.g. © SAP 2008 / SAP TechEd 08 / <COMP273> Page 52 . Raise exception with explicit object creation or re-raise a caught exception DATA excp TYPE REF TO cx_page_not_found. RAISE EXCEPTION excp.

Consists of Exactly one protected code area One or more exception handlers © SAP 2008 / SAP TechEd 08 / <COMP273> Page 53 . ENDTRY. CATCH cx_sy_file_open_mode INTO excp. CLOSE DATASET file. excp->filename. WRITE: 'Buffer successfully written'.ENDTRY DATA excp TYPE REF TO cx_sy_file_open_mode. TRY.. TRANSFER xbuffer TO file. 'is not open'. WRITE: 'File'. CATCH cx_sy_file_access_error WRITE: 'Other file IO exception occurred'. OPEN DATASET file FOR OUTPUT IN BINARY MODE.Catching Class-Based Exceptions Syntactical construct: TRY.

cx_fM ....cx_eN CATCH cx_f1 ..Protected Area TRY.. "– handler code for exceptions cx_f1 . Cx_fM [ INTO excp2 ]... cx_eN [ INTO excp1 ].. Protected area All statements between TRY and first CATCH Only exceptions that occur in protected area can be handled Handler code is not protected But TRY constructs can be nested © SAP 2008 / SAP TechEd 08 / <COMP273> Page 54 . ENDTRY. "– handler code for exceptions cx_e1 . "– any statements CATCH cx_e1 .

. "– handler code for exceptions cx_e1 ..cx_eN CATCH cx_f1 .. Exception handlers (CATCH clauses) Are checked from top to bottom Each can handle one or more exceptions Optional access to exception object by INTO clause © SAP 2008 / SAP TechEd 08 / <COMP273> Page 55 .cx_fN . "– handler code for exceptions cx_f1 ...Exception Handlers TRY. "– any statements CATCH cx_e1 .... ENDTRY. cx_fN [ INTO excp2 ]. cx_eN [ INTO excp1 ].

Grouping by Polymorphism Superclasses can be used in CATCH clauses to catch all exceptions of any subtype Order of clauses is important Order must be from 'special' to more 'general' exception CX_ROOT CX_SY_ARITHMETIC_ERROR CX_PAGE_NOT_FOUND CX_SY_ZERODIVIDE CX_SY_ARITHMETIC_OVERFLOW © SAP 2008 / SAP TechEd 08 / <COMP273> Page 56 .

Use the debugger to see how the code gets executed. Create a new test class with the name LTCL_EXCEPTIONS_TESTS. Provoke the exception CX_SY_ZERODIVIDE by trying to divide a number by zero.Exceptions – Exercise Exercise 5: Open the transaction SE80. write a test which makes sure that a) the system throws an exception when you try to divide a number by zero b) the system throws the exception CX_SY_ZERODIVIDE. Use the optional into clause to save the exception object into a variable. Create a new report ZTBEXERCISE5_<counter>. Now. Create a new test method with the name RAISE_EXCEPTION. Have a look at how ABAP Unit automatically catches exceptions. © SAP 2008 / SAP TechEd 08 / <COMP273> Page 57 . One hint the method CL_AUNIT_ASSERT=>FAIL() should be used in the test method.

Automatic Exception Propagation

TRY. dispatcher->show( a_page ). " -- More normal coding CATCH cx_page_not_found cx_misformed_url. " -- Error handling. ENDTRY. METHOD show. "IMPORTING a_page TYPE string TRY. retrieve( a_page ). " -- More normal coding CATCH cx_some_exception. " -- Error handling for some exception. CATCH cx_other_exception. " -- Error handling for other exception. ENDTRY. ENDMETHOD. METHOD retrieve. "IMPORTING a_page TYPE string … RAISE EXCEPTION TYPE cx_page_not_found … ENDMETHOD.
© SAP 2008 / SAP TechEd 08 / <COMP273> Page 58

How to Find the Right Exception Handler

Exception occurred

Inside protected area? yes Look for handler in corresponding TRY-block

no

yes

TRY-block found?

no

Runtime Error

Handler found? yes Process handler code
© SAP 2008 / SAP TechEd 08 / <COMP273> Page 59

no

Go up call hierarchy and look for outer TRY-block

Go to end of handler's TRY-block

How to Guarantee a Consistent State
Problem
Procedures are left premature Objects / application might be in an inconsistent state Example: allocated resources

Solution
Introduction of (optional) CLEANUP clause TRY. "– any statements CATCH cx_e1 ... cx_eN [ INTO excp1 ]. "– handler code for exceptions cx_e1 ..cx_eN ... CLEANUP [ INTO excp ]. "- optional "– statements ENDTRY.
© SAP 2008 / SAP TechEd 08 / <COMP273> Page 60

other exception. Free internal resources. METHOD show. some exception.Error handling. TRY. TRY. ENDTRY. retrieve( a_page ). " -. ENDMETHOD.Error handling for " -.Error handling for other exception. " -.Error handling for CATCH cx_some_exception. "IMPORTING a_page TYPE string … RAISE EXCEPTION TYPE cx_page_not_found … ENDMETHOD.Error handling for " -. "IMPORTING a_page TYPE string TRY.Error handling for CATCH cx_other_exception. CATCH cx_some_exception. CATCH cx_other_exception. ENDMETHOD. ENDMETHOD. CATCH cx_some_exception. " -. " -.Example CLEANUP Clause TRY. retrieve(a_page). some exception. some exception. CLEANUP.Error handling for other exception. METHOD show. some exception. retrieve( a_page ). " -. CATCH cx_some_exception. other exception.Error handling for CATCH cx_other_exception. " -. " -ENDTRY. ENDTRY. METHOD retrieve. © SAP 2008 / SAP TechEd 08 / <COMP273> Page 61 . dispatcher->show( a_page ). retrieve( a_page ). "IMPORTING a_page TYPE string METHOD show. "IMPORTING a_page TYPE string METHOD show.Error handling for CATCH cx_other_exception. "IMPORTING a_page TYPE string TRY. CATCH cx_page_not_found cx_misformed_url. ENDMETHOD. " -. ENDTRY. ENDTRY.

execution continues with next higher CLEANUP clause or handler code respectively CLEANUP clause must not be left abnormally No use of RETURN..CLEANUP Clause CLEANUP clause is processed if and only if exception Has occurred Is not caught in current TRY – construct Is going to be caught somewhere above in call hierarchy Technically spoken CLEANUP clause is processed during unwinding of the stack At the end of CLEANUP clause.. EXIT. CONTINUE . to leave the clause Exceptions inside of the CLEANUP clause must be handled locally © SAP 2008 / SAP TechEd 08 / <COMP273> Page 62 .

Benefits Users have only to deal with exceptions mentioned in a procedure's signature Compiler can check if an exception is either handled inside of a procedure or declared to leave it © SAP 2008 / SAP TechEd 08 / <COMP273> Page 63 .Declaring Exceptions Problem How do users of a procedure know which exceptions to expect? Solution Exceptions that are not handled inside of the procedure are part of the procedure's signature METHODS: show IMPORTING a_page TYPE string RAISING cx_page_not_found.

RAISING Clause Declaration in subroutines (forms). RAISING cx_e1 cx_e2 .. cx_eN Each class mentioned in RAISING clause implies all subclasses Compiler / extended syntax check warns if an exception is neither handled nor declared Compiler warning instead of error to ease change process At runtime a special exception is thrown (cx_sy_no_handler) if undeclared exception leaves procedure Original exception is no longer active (cannot be caught any more) © SAP 2008 / SAP TechEd 08 / <COMP273> Page 64 .... function modules and methods .

Exceptions in Procedure Declarations How to declare exceptions in class / function builder Use class-based exceptions © SAP 2008 / SAP TechEd 08 / <COMP273> Page 65 .

cx_sy_no_more_memory) Forcing the user to declare or catch such exceptions would be counter-productive Either procedures get cluttered with exception declarations Or users catch exceptions without having a proper handler Better solution: there are exceptions that don't need to be declared Compiler doesn't check if exception is handled (no static check at compile time) Runtime system doesn't check if exception was declared for a procedure if exceptions leaves it (no dynamic check at runtime) Consequence: users have to be aware that these exceptions may occur anywhere © SAP 2008 / SAP TechEd 08 / <COMP273> Page 66 .g. but are hard to be handled locally Typical examples: resource limitation and global errors (e. cx_sy_too_many_files.Limitations of Static Checking (1) Some exceptions may occur anywhere.

users can ensure that they will not occur They know(!) what they are doing or they can avoid error conditions beforehand Typical examples: parameter constraints (e. cx_sy_zerodivide. if the exception does occur? Solution: there are exceptions that must be declared if they can occur but they are not statically checked Compiler doesn't check if exception is handled Runtime system does check if the exception was declared if it tries to leave the procedure Consequence: if user was wrong (exception leaves procedure) an exception is thrown (cx_sy_no_handler) © SAP 2008 / SAP TechEd 08 / <COMP273> Page 67 . cx_misformed_url) Forcing the user to declare or catch such exceptions would be counter-productive Leads to empty handlers just to calm compiler down Problem: what happens.g.Limitations of Static Checking (2) For some exceptions.

Exception Class Hierarchy Three categories of exceptions All exceptions are derived from corresponding classes CX_ROOT CX_STATIC_CHECK CX_DYNAMIC_CHECK CX_NO_CHECK Signature statically checked by compiler and dynamically at runtime © SAP 2008 / SAP TechEd 08 / <COMP273> Page 68 Signature checked only at runtime Not in signature. never checked .

Exception Class Hierarchy Can be used in RAISING clause CX_ROOT CX_STATIC_CHECK CX_DYNAMIC_CHECK CX_NO_CHECK Signature statically checked by compiler and dynamically at runtime © SAP 2008 / SAP TechEd 08 / <COMP273> Page 69 Signature checked only at runtime Not in signature never checked .

get_longtext: returns textual description of exception (get_longtext available with SAP_BASIS 620) Automatic generation of constructor in global exception classes One optional parameter for each non-private attribute © SAP 2008 / SAP TechEd 08 / <COMP273> Page 70 .Exception Classes: Methods and Attributes Each exception class can define its own attributes Attributes can be of any type Are preferably read-only Methods inherited from cx_root get_source_position: returns position where exception has been raised get_text.

sap. CX_PAGE_NOT_FOUND Textid Page http://www.Chaining of Exceptions Attribute previous: Enables chaining of exceptions Example: undeclared exception leaves procedure Exception cx_sy_no_handler is raised CX_SY_NO_HANDLER Classname Previous CX_PAGE_NOT_FOUND Chaining can be employed explicitly RAISE EXCEPTION TYPE cx_some_exception EXPORTING previous = caught_exception.com/shop/ © SAP 2008 / SAP TechEd 08 / <COMP273> Page 71 .

sap.sap. get_longtext: Returns textual description of the exception Occurrences of ‘&ATTRIBUTE&' in text are substituted by attribute values CX_PAGE_NOT_FOUND Textid Page http://www.Exception Texts Attribute textid: Points to textual description of the exception Method get_text.com/shop/ © SAP 2008 / SAP TechEd 08 / <COMP273> Page 72 .com/shop/ 'No document at URL &PAGE&' No document at URL http://www.

DEMO © SAP 2008 / SAP TechEd 08 / <COMP273> Page 73 .

Exception Builder Default exception id has same name as exception class Substituted by attribute value © SAP 2008 / SAP TechEd 08 / <COMP273> Page 74 .

.Multiple Exception Texts They can be used to differentiate between related exceptions No need to define separate exception classes for sflight variants Should be really related all attributes have same meaning for all id's Handlers usually will not differentiate between id's Raise exception with different text RAISE EXCEPTION TYPE cx_aab_persistence EXPORTING textid = cx_aab_persistence=>cx_aab_.__flush_fail © SAP 2008 / SAP TechEd 08 / <COMP273> Page 75 ..

message number and the parameter mapping).Exception Text Repository Online Text Repository (OTR) Texts up to 255 characters supported Use of &ATTRIBUTE& in text for substitution Should not be used for exceptions with text in user interface Messages (T100) — available with SAP_BASIS 640 Texts no longer than 72 characters Only 4 parameters (&1 . (contains message class. but parameter in exception constructor is still called textid © SAP 2008 / SAP TechEd 08 / <COMP273> Page 76 .. &4) in text for substitution. definition of mapping necessary (parameter → attribute name) Can be directly used for user interface (MESSAGE) Technical: ─ Exception class implements IF_T100_MESSAGE ─ Attribute for text is IF_T100_MESSAGE~t100key..

Exceptions Based on Message Class

© SAP 2008 / SAP TechEd 08 / <COMP273> Page 77

Local Exception Classes 1/2
Local exception classes can be defined
In the most simple case just inherit from CX_STATIC_CHECK, CX_DYNAMIC_CHECK or CX_NO_CHECK (or any already existing exception class) Define a constructor if you want to pass values to attributes Without specifying attribute for text you will get a default text

Local exceptions might be useful
during the development phase or for prototyping in the implementation part of a software layer

Local exceptions should normally be handled locally in a software layer

© SAP 2008 / SAP TechEd 08 / <COMP273> Page 78

Local Exception Classes 2/2
Defining a text in local classes is quite tricky
Define constant for each exception id Constant refers to textual description (OTR key or T100 key) In constructor set attribute for exception text accordingly

OTR-Texts
For each exception id one constant of type SOTR_CONC Name is name of exception id, value is respective OTR GUID

T100-Texts
Implement IF_T100_MESSAGE For each exception id one constant of type SCX_T100KEY Values define msgid, msgno and parameter mapping

© SAP 2008 / SAP TechEd 08 / <COMP273> Page 79

Exceptions Within the Debugger Show exception object Display exception position © SAP 2008 / SAP TechEd 08 / <COMP273> Page 80 .

Exceptions Within the Debugger © SAP 2008 / SAP TechEd 08 / <COMP273> Page 81 .

Exceptions Within the Debugger You can tell the debugger to stop on certain exceptions Condition is valid for subclasses too ⇒ to stop on every exception. set breakpoint at CX_ROOT © SAP 2008 / SAP TechEd 08 / <COMP273> Page 82 .

Exceptions Within the Debugger Exception objects are only created if they are really accessed CATCH cx_some_exception INTO exc. exception objects are always created in debugger © SAP 2008 / SAP TechEd 08 / <COMP273> Page 83 . CLEANUP INTO exc. If set.

Exceptions Within the Old Debugger Show exception object Display exception position © SAP 2008 / SAP TechEd 08 / <COMP273> Page 84 .

situation "page not found": Exceptional ⇒ exception Don't use sy-subrc to pass the return code! © SAP 2008 / SAP TechEd 08 / <COMP273> Page 85 . situation "element to be deleted doesn't exist": Is element expected to exist? yes ⇒ exception. answer depends on model. situation "element not found": Neither exceptional nor an error ⇒ return code Method delete.) Examples Method find. no ⇒ return code Method show.Exceptions Versus Return Codes Don't use exceptions when return codes are more appropriate Ask yourself Is the situation really exceptional? Are we in an error condition? (No easy question.

not describe where the error occurred Choose appropriate name for exception class Define exception class as general as possible (→ define exception attributes). but as specific as necessary Always have in mind that someone might want to reuse your exception class… By raising instances of existing exception classes in new coding By inheriting from class or adding additional exception text ids Reuse exception only if it's really appropriate All attributes are meaningful and have the same meaning for all exception ids Exception text is suitable Reuse only for same (or very similar) error situation – if there is a good possibility that handlers might react differently to two error situations. using one exception class is not a good idea © SAP 2008 / SAP TechEd 08 / <COMP273> Page 86 .Enable Exception Reuse 1/2 Exception should represent the error.

Enable Exception Reuse 2/2 Example: We have two operations (methods) with the following error situations: modify modifies an entry in a database table. it is an error if the specified entry does not exist or if the modification would produce duplicate keys delete deletes an entry in a database table. it is an error if the specified entry does not exist (similarities with the ABAP statements modify and delete are intended) Example for bad exceptions cx_ex_modify_error and cx_ex_delete_error Example for good exceptions cx_ex_unknown_entry and cx_ex_duplicate_key Both exceptions have an attribute operation or they might inherit it from a common super-class © SAP 2008 / SAP TechEd 08 / <COMP273> Page 87 .

computing the free memory before creating a new object).. e.. by performing a (simple) test beforehand Examples: parameter constraints (cx_sy_zerodivide).Choosing the Right Exception Category 1/3 Can exception be precluded? CX_DYNAMIC_CHECK Yes No CX_STATIC_CHECK CX_NO_CHECK CX_DYNAMIC_CHECK: Programmers can avoid exception: they know that the exception will never occur at specific code positions. call sequence constraints or combination of both (cx_sy_file_open_mode) Note: if test beforehand is not natural or too expensive (e.g.g. this category is not the right one CX_STATIC_CHECK and CX_NO_CHECK: Programmer cannot preclude that exception will occur (without performing specific complicated tests beforehand) © SAP 2008 / SAP TechEd 08 / <COMP273> Page 88 .

it is easy to see who has not taken the exception into account: the procedure without the RAISING clause (which is listed in the short dump) Note: if most callers cannot handle the exception.g.. the declaration becomes counterproductive → these categories are not the right ones CX_NO_CHECK: Case-by-case analysis necessary to decide in which procedure the exception should have been caught. No handler (⇒ runtime error) might also be OK Handler might be difficult to write (e.Choosing the Right Exception Category 2/3 Responsibility for handling exception Declared → Clear CX_DYNAMIC_CHECK Undeclared CX_STATIC_CHECK CX_NO_CHECK CX_STATIC_CHECK and CX_DYNAMIC_CHECK: Clear responsibility: if exception leads to a runtime error. for exhausted resource) Handler can be far up in the call hierarchy (if there is just a global solution) © SAP 2008 / SAP TechEd 08 / <COMP273> Page 89 .

Choosing the Right Exception Category 3/3 Compiler checks are… More helpful CX_DYNAMIC_CHECK More harmful CX_STATIC_CHECK CX_NO_CHECK CX_STATIC_CHECK: Programmers are forced to react to exception by handling it or by propagating it Compiler warns if programmers have forgotten to do so Note: do not annoy programmers by forcing them to write handlers if there is no need to do so — they would do the worst: writing empty handlers CX_DYNAMIC_CHECK and CX_NO_CHECK: Programmers are free to choose how to take exceptions into account (in ways which a compiler might not recognize) Programmers might forget to take exception into account — there is no safety check by the compiler © SAP 2008 / SAP TechEd 08 / <COMP273> Page 90 .

.....Exceptions in Layered Software 1/2 Software is usually layered User Interface Interface to Layer n Implementation of Layer n ... .. Interface to Layer 1 Implementation of Layer 1 Interface to Layer 0 Implementation of Layer 0 Exceptions part of the layers' interfaces Abstraction in exceptions from bottom to top Bottom: more technically oriented Top: more semantic/user oriented © SAP 2008 / SAP TechEd 08 / <COMP273> Page 91 Abstraction .

not the implementation of the layer Two ways of abstraction Use more general exception class from the hierarchy in the RAISING clause instead of listing specific exceptions explicitly Catch exceptions that are implementation specific and map to appropriate new exceptions (use chaining to have a link to the original exception) But: mapping might be inappropriate for many exceptions of category CX_NO_CHECK (their specific handlers have no chance to catch the exception directly) Mapping of exceptions is usually preferred to generalization RAISE EXCEPTION TYPE cx_level1_exception EXPORTING previous = exc_level0. © SAP 2008 / SAP TechEd 08 / <COMP273> Page 92 .Exceptions in Layered Software 2/2 User of a layer should only know the interface.

cancel the money transfer if the item is out-of-stock) Set the object to a consistent state TRY-construct without a handler possible METHOD store_result OPEN DATASET file . process_data( )...g.Guarantee a Consistent State Always use CLEANUP Always anticipate exception propagation of called procedures (esp. close a file after a file-open) Ensure atomicity of actions by canceling the performed sub-actions (e. © SAP 2008 / SAP TechEd 08 / <COMP273> Page 93 . of category CX_NO_CHECK) De-allocate global resources after having them allocated (e. CLEANUP.. TRY. ENDMETHOD. ENDTRY.g. CLOSE DATASET file.. CLOSE DATASET file.

e. e. e. if you cannot handle it if some attribute has specific values (remember: no handler leads to automatic propagation) Map the exception to a more abstract exception (use chaining!) If necessary.g. an old exception or an exception having the right category Write a log entry and proceed with the next sub-task.g.g. when performing individual tests in a test suite At user interface: display a corresponding message and list options for various ways how to proceed … © SAP 2008 / SAP TechEd 08 / <COMP273> Page 94 .Writing Correct Exception Handlers 1/2 What to do in an exception handler Fix things up and retry your operation (avoid infinite loops!). map the exception to a return code. read value from the database instead of looking it up in a corrupt cache Re-raise the exception... delete some temporary files if the file system is full and retry writing the file Use an alternative way to produce the same (or a similar) result.g.. e..

catching CX_ROOT or CX_NO_CHECK is almost never appropriate. catching CX_STATIC_CHECK and CX_DYNAMIC_CHECK is also critical © SAP 2008 / SAP TechEd 08 / <COMP273> Page 95 .g. if you write a global dispatcher)..Writing Correct Exception Handlers 2/2 What to do in an exception handler Never do nothing ⇒ empty handlers are always wrong. not a common super-class But: keep abstraction (via generalization) in mind Except at top-level (e. do not write a handler (exceptions are automatically propagated to someone who might know what to do) Catch exceptions selectively Catch only exceptions for which you can write a useful handler When writing a handler for two or more exception classes. list these classes in the CATCH clause. the extended syntax checks looks for empty handlers If you do not know what to do.

but is often not severe enough to terminate a whole service.g. RESUMABLE(cx) © SAP 2008 / SAP TechEd 08 / <COMP273> Page 96 .Resumable Exceptions Motivation Error situation can often be handled only outside service which detects it (→ exceptions would be optimal). test by checking attribute is_resumable) Intermediate callers can control resumption of propagated exceptions → RAISING . e. in mass-data processing (→ existing exceptions not usable). Resumable exceptions Service can specify that it is able to continue doing its work → RAISE RESUMABLE EXCEPTION Handler can decide whether to terminate the service (the default) or to resume → RESUME (only possible if allowed by raising statement and all intermediate callers...

The exception ZCX_FILE_ALREADY_EXISTS is resumable so make sure you use the correct syntax for the catch block. React appropriately to all exceptions. Find out what exceptions the method ADD_FILE might throw. Have a look at the class ZCL_FILESYSTEM which is a very simple fake implementation of a file system. Create a new report ZTBEXERCISE6_<counter>. Optional: Have a look at the exception ZCX_FILE_ALREADY_EXISTS and find out how it uses a message class + a class attribute to generate the exception text. If the file already exists overwrite it by resuming the method call. use the instance to add a new file to the file system. In the end make sure by checking the return value of the method ADD_FILE that the file was successfully added to the file system. Make sure you catch all exceptions. Debug your application and observe the program flow. Open the report ZTBEXERCISE6_BASE and copy the local test class LTCL_ADV_EXCEPTIONS_TESTS into the newly created report.Exceptions – Exercise Exercise 6: Open the transaction SE80. © SAP 2008 / SAP TechEd 08 / <COMP273> Page 97 . Start implementing the test method RETRY_RESUME_EXCEPTION by creating an instance of the class ZCL_FILESYSTEM. Now. If there is no space on the file system left call the appropriate method to empty the recycle bin and retry.

(Douglas Thain) © SAP 2008 / SAP TechEd 08 / <COMP273> Page 98 .Conclusion Exceptions enable programmers to write robust applications: the software is be able to recover from faults without substantially increasing the code complexity. but Error handling code (whether using exceptions or not using them) is more likely to contain software bugs than any other part of an application (increased complexity. difficult to test). The mere use of exceptions in a program does not imply a disciplined error management.

1. Coverage Analyser 3.3.Agenda 1. Asserts © SAP 2008 / SAP TechEd 08 / <COMP273> Page 99 . ABAP Unit Browser 3.1. Robust code 3.2.2. Dynamic tests 2. Static tests 1. Exceptions 3. Code Inspector 2. Test Driven Development with ABAP Unit 2.1.

some_code. some_code. * the following condition should hold: v < 300000 more_code. Assertions are available with WEB AS 6. ASSERT v < 300000. Better than an informal comment: special statement – assertion some_code. more_code. " nothing is faster than light more_code.20 SP29 © SAP 2008 / SAP TechEd 08 / <COMP273> Page 100 . more_code.Assertions: Introduction To write correct and maintainable programs… … make your assumptions and intentions explicit some_code.

© SAP 2008 / SAP TechEd 08 / <COMP273> Page 101 .Assertions Definition An assertion is a condition (Boolean expression) which must be true during program execution Program language construct which allows to verify consistent state by checking explicit assumptions at specific points during the execution of the program ABAP statement ASSERT <log_expr>.

Assertions ASSERT <log_expr>. © SAP 2008 / SAP TechEd 08 / <COMP273> Page 102 . An assertion is violated if the expression <log_expr> does not evaluate to true when processing the ASSERT statement This indicates an error in the coding Violating an (always active) assertion terminates the program with runtime error ASSERTION_FAILED Assertions make implicit errors explicit.

Assertions: Benefits During Development and Test unexpected behavior : assertion system state system state normal termination consistent state program flow consistent state program flow Execution is terminated as soon as incorrect state is detected limit the effect of bugs © SAP 2008 / SAP TechEd 08 / <COMP273> Page 103 enhance program correctness normal termination runtime error .

Assertions: Benefits During Development and Test : assertion system state undetected error normal termination system state consistent state program flow consistent state program flow Also finds bugs which only temporarily cause an incorrect state find more bugs © SAP 2008 / SAP TechEd 08 / <COMP273> Page 104 enhance program correctness normal termination runtime error .

Assertions: Additional Benefits During Maintenance runtime error or unexpected behavior system state ? Where did things start going wrong consistent state not stated explicitly program flow system state : assertion consistent state program flow Assertions provide insight into expected system behavior by making assumptions explicit enhances maintainability © SAP 2008 / SAP TechEd 08 / <COMP273> Page 105 .

DEMO © SAP 2008 / SAP TechEd 08 / <COMP273> Page 106 .

Problem evaluating the assertion might be expensive ⇒ not feasible in productive system © SAP 2008 / SAP TechEd 08 / <COMP273> Page 107 .Assertions in Productive Systems Example METHOD sort_by_name. ENDMETHOD. ASSERT itab->is_sorted_by_name( ) = abap_true. the_sorting_algorithm. complicated_stuff.

do not evaluate assertions unless a problem has to be investigated activatable assertions METHOD sort_by_name. testing and maintenance in productive systems. ENDMETHOD. the_sorting_algorithm. ASSERT ID test_sorting CONDITION itab->is_sorted_by_name( ) <> ' '. complicated_stuff. © SAP 2008 / SAP TechEd 08 / <COMP273> Page 108 .Assertions in Productive Systems Solution evaluate expensive assertions only during development.

By specifying addition ID <group> the ASSERT statement is linked to checkpoint group <group> and can be activated Activatable assertions are inactive by default.Assertions That Can be Activated ASSERT ID <group> CONDITION <log_expr>. without degrading application performance in a productive environment © SAP 2008 / SAP TechEd 08 / <COMP273> Page 109 . which are always active and can not be disabled) Inactive ASSERT statements are ignored. the corresponding conditions are not evaluated Time consuming checks can be coded into assertions that can be activated. unless activation is set for the corresponding checkpoint group (in contrast to always active assertions.

Checkpoint Groups Checkpoint Group is a new workbench object type which is embedded into WB navigation and cross reference. It is used to control activatable checkpoint statements (e. ASSERT) Associated maintenance transaction (SAAB) can be called directly or via object navigator Transaction SAAB Activation of activatable Assertion is set dynamically via the specified checkpoint group by means of activation settings Assertions can be activated in a running system © SAP 2008 / SAP TechEd 08 / <COMP273> Page 110 .g.

© SAP 2008 / SAP TechEd 08 / <COMP273> Page 111 .Activation Settings: Overview An activation setting consists of three components Scope: To which ASSERT statements does it apply? Target: For which sessions is it effective? Mode: What will happen when the assertion is violated? Checkpoint Group AAB_DEMO User TESTUSER Server * Mode ABORT An activatable ASSERT statement is ignored unless an activation setting with matching scope and target specification is found.

© SAP 2008 / SAP TechEd 08 / <COMP273> Page 112 . Checkpoint Group AAB_DEMO User TESTUSER Server * Mode ABORT ASSERT ID some_other_group CONDITION num < 100.Activation Settings: Scope A setting only applies to those ASSERT statements which are linked to the specified checkpoint group ASSERT ID aab_demo CONDITION is_sorted( ) = abap_true.

Activation Settings: Target Checkpoint Group AAB_DEMO User TESTUSER Server * Mode ABORT User * User * User TESTUSER Server * Server pwdf0195 Server * All users on all servers: Global activation All users on specified server: Server specific activation Specified user on all servers: User specific activation Special case: Personal activation All target settings are client dependent (as of 7.00) © SAP 2008 / SAP TechEd 08 / <COMP273> Page 113 .

Activation Settings: Mode Checkpoint Group AAB_DEMO User TESTUSER Server * Mode ABORT What will happen when the assertion is violated? ABORT Runtime error ASSERTION_FAILED BREAK Program execution is stopped (Debugger) (Two variant BREAK/LOG and BREAK/ABORT define what to do during batch run instead starting the debugger) LOG Violation is logged INACTIVE Violation is ignored (Activation Setting with Mode INACTIVE will be ignored) Assertions which are always active (no ID <group> specified) always run in mode ABORT. © SAP 2008 / SAP TechEd 08 / <COMP273> Page 114 .

prepared to encounter short dump Productive user. non-interactive BREAK ABORT LOG Support user. analyses short dumps and monitors assertion logs © SAP 2008 / SAP TechEd 08 / <COMP273> Page 115 . prepared to jump into debugger Productive user.Activation Mode Activation mode and maintenance scenarios Maintenance Short term. non disturbed Support user. interactive Long term.

Multiple Activation Settings Checkpoint Group AAB_DEMO AAB_DEMO AAB_DEMO AAB_DEMO User * * * TESTUSER 1 Server * SERVER1 SERVER2 * Mode ABORT LOG BREAK LOG Multiple settings with the same scope (checkpoint group) but different target (user. server) can be specified simultaneously precedence rule defines which setting will be used to determine the activation mode © SAP 2008 / SAP TechEd 08 / <COMP273> Page 116 .

Multiple Activation Settings: Precedence Rule User specific setting supersedes server specific setting supersedes global setting USER2 on SERVER3 USER2 on SERVER1 USER2 on SERVER2 Checkpoint Group AAB_DEMO AAB_DEMO AAB_DEMO AAB_DEMO User * * * USER1 Server * Mode ABORT SERVER LOG 1 SERVER BREAK 2 * LOG USER1 on SERVER2 © SAP 2008 / SAP TechEd 08 / <COMP273> Page 117 .

DEMO © SAP 2008 / SAP TechEd 08 / <COMP273> Page 118 .

Maintaining Settings: Personal Activation Transaction SAAB Set personal activation here © SAP 2008 / SAP TechEd 08 / <COMP273> Page 119 .

Maintaining Settings: User/Server Specific Activation Transaction SAAB User-specific Settings Break Break/Log Break/Abort Abort Server-specific Settings © SAP 2008 / SAP TechEd 08 / <COMP273> Page 120 .

especially in productive environments Performance is possibly degraded Use non-personal activation only after careful consideration non-personal settings will be sys-logged Authority checks performed on activation Personal activation requires debug authorization (display) Non-personal activation requires debug authorization (change) and process administration authorization © SAP 2008 / SAP TechEd 08 / <COMP273> Page 121 .Maintaining Settings: Considerations Be careful with all kinds of non-personal settings Users will be disturbed if their application stops or terminates suddenly.

Assertion Log A dedicated logging facility exists for assertion violations Switched on via activation mode LOG Log entries are viewed using transaction SAAB Transaction SAAB © SAP 2008 / SAP TechEd 08 / <COMP273> Page 122 .

Assertion Log: Subkey
To conserve space, we use aggregation
Log entries are aggregated for same ASSERT statement Information is only available for last violated assertion

Addition SUBKEY to reduce aggregation
ASSERT ID group SUBKEY subkey CONDITION cond Log entries are aggregated for same ASSERT statement with the same subkey value

© SAP 2008 / SAP TechEd 08 / <COMP273> Page 123

Assertion Log: Fields
Default log information
Checkpoint group Source position: program, include, line number, procedure Violation count (aggregation) Date and time of last violation

Addition FIELDS for additional information
ASSERT ID group FIELDS f1 … fn CONDITION cond names and values of fields f1 … fn are stored in the log when running in ABORT mode, field names and values are listed in runtime error ASSERTION_FAILED

© SAP 2008 / SAP TechEd 08 / <COMP273> Page 124

Activation Variants
Reusing (complex) activation settings
When working with a set of checkpoint groups, you may want to store your complex settings You may want to transport the stored settings In order to be reusable by other users, the stored settings must not contain target specifications Activation Variant

An activation variant is a workbench object containing template settings for a list of checkpoint groups. The target specification (user, server) is not stored in the activation variant, but has to be specified when activating via the variant.

© SAP 2008 / SAP TechEd 08 / <COMP273> Page 125

Maintaining Activation Variants Transaction SAAB List of checkpoint groups (scope specification) Corresponding modes © SAP 2008 / SAP TechEd 08 / <COMP273> Page 126 .

Variant is expanded and setting is applied for each contained checkpoint group. © SAP 2008 / SAP TechEd 08 / <COMP273> Page 127 .Variant Activation Transaction SAAB Activation target is specified when activation variant is activated.

regardless of the respective linkage to individual checkpoint groups Precedence rule: Setting via compilation unit supersedes setting via checkpoint group © SAP 2008 / SAP TechEd 08 / <COMP273> Page 128 . All activatable ASSERT statements within the specified compilation unit are controlled with such a setting.Scope Definition by Compilation Unit Normally the scope of an activation setting is specified using a checkpoint group. class or function group). In some cases it may be advantageous to specify the scope using a compilation unit (program.

Scope Definition by Compilation Unit: Example ASSERT ID A ASSERT ID B ASSERT ID D ASSERT ID E ASSERT ID F ASSERT ID A ASSERT ID C report x application ASSERT ID A class y ASSERT ID E function group z Activation mode ABORT for checkpoints in group A Activation mode BREAK for checkpoints in class y © SAP 2008 / SAP TechEd 08 / <COMP273> Page 129 .

Specifying Settings for a Compilation Unit Settings for compilation units can only be specified using activation variants Transaction SAAB Transaction SAAB Compilation units © SAP 2008 / SAP TechEd 08 / <COMP273> Page 130 .

as the developer explicitly declares his assumptions using assert conditions ABAP assertions are either always active.Conclusions ABAP assertions support the developer in writing correct code Code instrumented with assertions is easier to support and maintain. or can be activated on the fly and without program modification or recompilation (optionally user or server specific) Activation can be controlled via checkpoint group or compilation unit © SAP 2008 / SAP TechEd 08 / <COMP273> Page 131 .

Fuel your Career with SAP Certification What the industry is saying “Teams with certified architects and developers deliver projects on specification.” 2008 IDC Certification Analysis “82% of hiring managers use certification as a hiring criteria. and that’s what matters most to customers. and on budget more often than other teams. SAP Certified Professional Take advantage of the enhanced. on time.”* Conny Dahlgren. expanded and multi tier certifications from SAP today! © SAP 2008 / SAP TechEd 08 / <COMP273> Page 132 .” 2008 SAP Client Survey “SAP Certified Application Professional status is proof of quality.

Thank you! © SAP 2008 / SAP TechEd 08 / <COMP273> Page 133 .

and do not take the handouts for the following session. Thank You ! © SAP 2008 / SAP TechEd 08 / <COMP273> Page 134 .Feedback Please complete your session evaluation. Be courteous — deposit your trash.

visit us at the Community Clubhouse or at www.S. and commercialization license to the complete SAP NetWeaver software platform Automatic notification for patches and updates Continuous learning presentations and demos to build expertise in each of the SAP NetWeaver platform components A personal SAP namespace SAP NetWeaver Content Subscription: (available globally) An online library of continuous learning content to help build skills. Starter Kit To learn more or to get your own SDN Subscription.com/irj/sdn/subscriptions © SAP 2008 / SAP TechEd 08 / <COMP273> Page 135 . and Germany) A one year low cost. SDN Software Subscriptions: (currently available in U. to keep you at the top of your profession. test. an annual license to the complete SAP NetWeaver platform software. development. related services. and educational content.Building Your Business with SDN Subscriptions SDN Subscriptions offers developers and consultants like you.sap.sdn.

Duet. © SAP 2008 / SAP TechEd 08 / <COMP273> Page 136 . SAP assumes no responsibility for errors or omissions in this document. or transmitted in any form or for any purpose without the express prior written permission of SAP AG. Diese Publikation kann von SAP jederzeit ohne vorherige Ankündigung geändert werden. Die gesetzliche Haftung bei Personenschäden oder Produkthaftung bleibt unberührt. Einige von der SAP AG und deren Vertriebspartnern vertriebene Softwareprodukte können Softwarekomponenten umfassen. Please note that this document is subject to change and may be changed by SAP at any time without notice. xApps. This document is a preliminary version and not subject to your license agreement or any other agreement with SAP. developments. or other items contained within this material. SAP entsteht aus dieser Publikation keine Verpflichtung zu einer bestimmten Geschäfts. The information contained herein may be changed without prior notice. SAP haftet nicht für entstandene Schäden. und uneingeschränkt für konkrete. bereitgestellt.oder Produktstrategie und/oder bestimmten Entwicklungen. Dies gilt u. National product specifications may vary. indirect. This limitation shall not apply in cases of intent or gross negligence. Weitergabe und Vervielfältigung dieser Publikation oder von Teilen daraus sind.. SAP has no control over the information that you may access through the use of hot links contained in these materials and does not endorse your use of third-party Web pages nor provide any warranty whatsoever relating to third-party Web pages.Copyright 2008 SAP AG All Rights Reserved No part of this publication may be reproduced or transmitted in any form or for any purpose without the express permission of SAP AG. ByDesign. The statutory liability for personal injury and defective products is not affected. fitness for a particular purpose. Diese Einschränkung gilt nicht bei Vorsatz oder grober Fahrlässigkeit. die aus der Nutzung dieser Materialien entstehen können. R/3. either express or implied. R/3. Diese Publikation wird ohne jegliche Gewähr. Produkte können länderspezifische Unterschiede aufweisen. No part of this document may be reproduced. product strategy. Data contained in this document serves informational purposes only. SAP. The information in this document is proprietary to SAP. or consequential damages that may result from the use of these materials. zu welchem Zweck und in welcher Form auch immer. SAP does not warrant the accuracy or completeness of the information. SAP NetWeaver. Alle Rechte vorbehalten. In dieser Publikation enthaltene Informationen können ohne vorherige Ankündigung geändert werden. text. Duet. special. hinsichtlich der Gewährleistung der Marktgängigkeit und der Eignung für einen bestimmten Zweck sowie für die Gewährleistung der Nichtverletzung geltenden Rechts. a. links. weder ausdrücklich noch stillschweigend. SAP NetWeaver. ByDesign. graphics. All other product and service names mentioned and associated logos displayed are the trademarks of their respective companies. unterliegen nicht dem Einfluss von SAP. This document is provided without a warranty of any kind. Alle anderen in diesem Dokument erwähnten Namen von Produkten und Services sowie die damit verbundenen Firmenlogos sind Marken der jeweiligen Unternehmen. SAP Business ByDesign. xApp. nur mit ausdrücklicher schriftlicher Genehmigung durch SAP AG gestattet. including but not limited to the implied warranties of merchantability. PartnerEdge und andere in diesem Dokument erwähnte SAP-Produkte und Services sowie die dazugehörigen Logos sind Marken oder eingetragene Marken der SAP AG in Deutschland und in mehreren anderen Ländern weltweit. xApp. or non-infringement. This document contains only intended strategies. besondere und mittelbare Schäden oder Folgeschäden. SAP Business ByDesign. and/or development. Texte. ohne die ausdrückliche schriftliche Genehmigung durch SAP AG nicht gestattet. Des Weiteren übernimmt SAP keine Garantie für die Exaktheit oder Vollständigkeit der Informationen. Die Angaben im Text sind unverbindlich und dienen lediglich zu Informationszwecken. die nicht Ihrem gültigen Lizenzvertrag oder anderen Vereinbarungen mit SAP unterliegt. Die in dieser Publikation enthaltene Information ist Eigentum der SAP. Bei dieser Publikation handelt es sich um eine vorläufige Version. SAP. SAP shall have no liability for damages of any kind including without limitation direct. xApps. Some software products marketed by SAP AG and its distributors contain proprietary software components of other software vendors. Diese Publikation enthält nur vorgesehene Strategien. Dies gilt u. die Eigentum anderer Softwarehersteller sind. und SAP unterstützt nicht die Nutzung von Internetseiten Dritter durch Sie und gibt keinerlei Gewährleistungen oder Zusagen über Internetseiten Dritter ab. a. Die Informationen. Links und sonstigen in dieser Publikation enthaltenen Elementen. zu welchem Zweck und in welcher Form auch immer. Entwicklungen und Funktionen des SAP®-Produkts. auf die Sie möglicherweise über die in diesem Material enthaltenen Hotlinks zugreifen. Weitergabe und Vervielfältigung dieser Publikation oder von Teilen daraus sind. aber nicht ausschließlich. and functionalities of the SAP® product and is not intended to be binding upon SAP to any particular course of business. SAP übernimmt keine Haftung für Fehler oder Auslassungen in dieser Publikation. Grafiken. copied. PartnerEdge and other SAP products and services mentioned herein as well as their respective logos are trademarks or registered trademarks of SAP AG in Germany and in several other countries all over the world.