Try and Catch in Apex

Sample Code:


Visualforce page:



<apex:page standardController=”Account” extensions=”sample”>
    <apex:form >           
        <apex:pageMessages />
        <apex:pageBlock >
            <apex:pageBlockSection >
                <apex:pageBlockSectionItem >
                    Account Name:  
                </apex:pageBlockSectionItem>
                <apex:pageBlockSectionItem >
                    <apex:inputField value=”{!Account.Name}”/>
                </apex:pageBlockSectionItem>
            </apex:pageBlockSection>
            <apex:pageblockButtons >
                <apex:commandButton value=”Save” action=”{!add}”/>
            </apex:pageblockButtons>
        </apex:pageBlock>        
    </apex:form>
</apex:page>



Apex Controller:


public class sample
{
    public Account acc;
    public sample(ApexPages.StandardController controller)
    {
        this.acc = (Account)controller.getRecord();
    }

    public void add()
    {   
        try
        {
            insert acc;
        }
        Catch(Exception e)
        {         
            ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR,e.getMessage());
        }
    }           
}




Output:

 
Cheers!!!

Leave a Reply