i think one of best solution for generate code is using template engine like freemarker.
for using try catch or if else and some other expression in it using like this
<#attempt>
attempt block
<#recover>
recover block
</#attempt>
<#if x == 1> x is 1
<#elseif x == 2> x is 2
<#elseif x == 3> x is 3
</#if>
<#list fields as field>
<#list>
this template generate fileds for hibernate hbm.xml
<#list fields as field>
<#attempt>
<#if "${field.type.superclass}"=="class org.model.BaseEntity">
<many-to-one name="${field.name}" column="${field.name}" entity-name="${field.type.name}" not-null="true" />
<#else>
<property column="${field.name}" name="${field.name}" type="${field.type.simpleName}" not-null="false" />
</#if>
<#recover>
<property column="${field.name}" name="${field.name}" type="${field.type.simpleName}" not-null="false" />
</#attempt>
</#list>