Creating a function module and using it [Tutorial]

Function modules form a very important part in Modularization of the code. They are used to reduce the redundancy of code , improves debugging and readability of the program. The following tutorial explains in depth how to create your own custom function module(FM) and using it. 

Go to SE37.
First lets create a function group to hold all our function modules.
In SE37, navigate to Goto>> Function Groups >> Create Group.




 Give the name of the function group

That’s it. Now we will create a function module. Same SE37 transaction create a FM zau_getwerks.


 Give function group name we just created and give a short text for the FM

 We are creating this FM which accepts a material number and gives the plant details for that material.
Create a import parameter lv_matnr of type matnr. We can make it pass by value also by checking Pass by value. By default it is pass by reference only. If optional is checked then passing this parameter is not mandatory in the program.
Import Parameters - FM
Import Parameters - FM
Here I will create a output table  named output which is having a structure of zty_material.
Create a zty_material structure from SE11 . Data type >> Create structure and add matnr and werks component to that structure.
Tables in FM
Tables in FM 
We will add exceptions now. Exceptions provide a easy way for error handling in FMs. We will create 2 FM’s
One FM when we enter invalid material and another when data is not present related to plant.(No data in marc table)
Exceptions in FM
Exceptions in FM

 Now the main coding/logic part of the program. It’s a simple select statement. And we are checking sy-subrc to check whether we obtained data or not. If no data is fetched then we raise appropriate exceptions by using RAISE command.
Source Code FM
Source Code FM

 Activate the FM.


Now activate the FM and test the FM by clicking executes. Pass a material number and see the output
Test FM
Test FM


FM Output
FM Output


Now lets create a Z program which uses the FM we created.




That’s it. It’s as simple as that. Every exception is given numbers by default and we can check sy-subrc for these numbers to identify the exception.

Running Report
Report Output