Exception Handling In Salesforce Apex Classes

An exception is a special condition that changes the normal flow of program execution. That is, it’s when something bad happens that the program can’t deal with during execution. Exceptions are the language’s way of throwing up its hands and saying, I can’t deal with this, you need to handle those exceptions. we have three methods to catch this exceptions.

Apex allows to handle your exceptions, and write code to gracefully recover from an error. Apex uses the Try, Catch, Finally construct common to many other programming languages.

Try: If an exception occurs within the try block, that exception is handled by an exception handler associated with it. To associate an exception handler with a try block, you must put a catch block after it.
Catch: Each catch block is an exception handler that handles the type of exception indicated by its argument. The argument type, ExceptionType , declares the type of exception that the handler can handle and must be the name of a class that inherits from the Throwable class. The handler can refer to the exception with name.
Finally: This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling it allows the programmer to avoid having cleanup code accidentally bypassed by a return , continue , or break.

Simply You “try” to run your code. If there is an exception, you “catch” it and can run some code, then you can “finally” run some code whether you had an exception or not.

Here is an example of what these statements look like and the order in which they should be written:

try {
    // Perform some database operations that 
    //   might cause an exception.
} catch(DmlException e) {
    // DmlException handling code here.
} catch(Exception e) {
    // Generic exception handling code here.
} finally {
    // Perform some clean up.

Difference between rendered, renderAs and reRender in Visualforce Page

Rendered : It’s a Boolean value and the default value is always true, It works like “display” property of CSS. It is used to place condition for a component(field, outputpanel, section etc), that will show or not on page. (If it is true, it displays the block else it will be hidden).

For Example:
Visualforce Page:
In the controller we need to have get method to assign the value for this variable.

<apex:inputField value="{obj.Filed__c}" Rendered="{!val == true}"/>


public boolean val {get;set;}

val = true;

Rerender: After Ajax which component should be refreshed. For this we need to assign id to field, sections or a block. It’s available on commandlink, commandbutton, actionSupport etc.

For Example:
Visualforce Page:

    <apex:inputField value="{!TestValue}" >   
        <apex:actionSupport event="onchange" rerender="Id1,Id2,Id3,Id4" action="{!TestMethod}" >
            <apex:param name="Para" value="{!rowNum}" assignTo="{!IndexValue}" />

Here in actionSupport rerender attribute Id1,Id2,Id3,Id4 are the id’s of field and sections.

RenderAs: It is used for visualforce page show as pdf, excel or any other standard document format.

For Example:
Visualforce Page:

<apex:page controller="TestController" rederAs="pdf">

Custom Settings in Salesforce

Salesforce.com introduced Custom Settings in Winter ’10 which allows you to store custom data sets and associate them on an org-wide, profile or user basis. Custom settings data is exposed in the application cache and do not count against SOQL limits when fetched. This data can then be used by formula fields, validation rules, Apex, and the SOAP API.

Custom Settings support only Checkbox, Currency, Date, Date/Time, Email, Number, Percent, Phone, Text, Text Area, and URL field types. You can’t create Formula and Picklist, as well as field types that define relationships to other objects, like Lookup and Master/Detail. You can’t create lookups from Custom Objects to Custom Settings either. No Page layouts, record types, validation rules, triggers and workflow rules can be used on Custom Settings.

There are two types of custom settings:

List Custom Settings: It provides a reusable set of static data that can be accessed across your organization. If you use a particular set of data frequently within your application, putting that data in a list custom setting streamlines access to it. Data in list settings does not vary with profile or user, but is available organization-wide.

Hierarchy Custom Settings: Hierarchical Custom Settings are defined once and can hold a unique set of values for the Organization, each Profile or each individual User. Salesforce automatically grabs the lowest level of setting for the running user when a getInstance() call is made, or when accessed in a configuration such as a Validation Rule, Workflow or Formula Field. Only Hierarchical settings can be accessed declaratively whereas List settings are for Apex/Visualforce only.

Limitation of Custom Setting:

  • Maximum total data of 10 MB, but if you have less than 10 license users, multiply 1 MB with number of users.
  • 300 fields per custom setting..
  • Can’t share a custom setting record.
  • No owner assigned for each custom setting record.
  • Each custom setting counts against the total number of custom objects available for your organization.

Note: If you include custom settings in your distributed package you’ll need to build in some scripts which populate the settings with data after the package has been installed.

Difference between Custom Objects and Custom Settings

Custom Objects:

  • Custom Objects are custom database tables that allow to store information to your organization.
  • All Custom field types supported.
  • Records are updated by users.
  • Data stored in database.
  • Requires lookup or master-detail relationship to reference from another object.
  • Counts against cross-object reference limit when used in formulas.
  • Custom Objects are SOQL expensive.
  • We can use Page layouts, record types, validation rules, triggers and workflow rules on Custom Objects.

Custom Settings:

  • Custom Settings are similar to Custom Objects and enable application developers to create custom sets of data, as well as create and associate custom data for an organization, profile, or specific user. We can say Custom Settings are like configuration file that we used to have.
  • Custom Settings support only Checkbox, Currency, Date, Date/Time, Email, Number, Percent, Phone, Text, Text Area, and URL field types.
  • Records are updated by admins or developers.
  • Cached in memory (limited to 2mb).
  • No relationship field required.
  • Not a cross-object reference.
  • Custom Settings are SOQL inexpensive.
  • No Page layouts, record types, validation rules, triggers and workflow rules can be used on Custom Settings.

External Ids in Salesforce

What is External Ids?
An External Id is a custom field that has the “External Id” attribute, meaning that this filed is a primary key and it contains unique record identifiers from a system outside of Salesforce. Salesforce allows up to 3 fields as External Id and these fields must be text, number or email field types.
What is the use of External Ids?
Basically we use “External Id” to match on for updates. When we perform upsert or update, we can match on this “External Id” field. External Id is a manual record Id will be used to integrate with external system.

What is the advantage of External Ids?

  • The import wizard will detect existing records in Salesforce that have the same External Id.
  • When using the upsert command during data loading, we can reference the External Id field instead of the Salesforce Id.
  • When we load data from external systems, We can use External Ids to prevent duplicate records from being created as a result of the import operation.
  • Fields marked as External Ids are searchable in the sidebar search.