Expection Handling
Expection Handling
Exception handling refers to the mechanism that allows developers to manage and
respond to runtime errors in their code gracefully. Proper exception handling is crucial
for building robust applications that can handle unexpected situations without crashing
or causing data corruption.
Exception:
Try-Catch Block:
Throw Statement:
If an exception occurs, the throw statement can be used to pass the exception
to a higher level in the call stack, or to generate a custom exception.
Finally Block:
N.Veera Raghavamma
Types of Exceptions:
● Custom Exceptions: You can define your own exception classes by extending
the Exception class to handle specific business logic issues.
try {
insert acc;
} catch (DmlException e) {
} catch (Exception e) {
} finally {
N.Veera Raghavamma
System.debug('This will always run, even if an exception is
thrown.');
1. Try Block:
This block contains the code that may throw an exception. Salesforce executes the
code in the try block and looks for any exceptions.
try
2. Catch Block:
If an exception is thrown, the catch block catches and handles it. You can have multiple
catch blocks for different types of exceptions.
catch (DmlException e)
N.Veera Raghavamma
catch (QueryException e)
3. Finally Block:
The finally block contains code that will always execute, regardless of whether an
exception occurred or not. It’s often used for cleanup actions like closing resources or
logging.
finally
Custom Exceptions
You can create custom exceptions in Salesforce to represent specific business logic
errors.
if (accountName == null) {
N.Veera Raghavamma
throw new CustomBusinessException('Account name
cannot be null');
insert acc;
Do not leave catch blocks empty. Always log or take corrective action. For example:
catch (DmlException e) {
If there are resources that need to be released or actions that must be taken regardless
of success or failure, put them in the finally block.
N.Veera Raghavamma
Logging and Debugging:
Always log exceptions with useful information (like stack traces or error messages) to
help diagnose the issue. Use System.debug() or platform logging features.
Sometimes you might want to handle an exception and then rethrow it to be handled at
a higher level.
catch (Exception e)
throw e;
Only wrap the code that is prone to errors in a try-catch block. Wrapping large chunks of
code can make it harder to pinpoint issues.
N.Veera Raghavamma
Example of Complex Exception Handling:
N.Veera Raghavamma