Most Salesforce developers just throw exceptions… But is that enough?

Introduction

Handling errors properly is crucial for building robust and reliable applications. Many developers know how to throw exceptions, but not everyone understands why catching them is often the better approach. In this article, we’ll explore the importance of catching exceptions, how execution flow works in try-catch-finally, and what happens when you don’t handle exceptions properly. By the end, you’ll have a solid understanding of when and how to use exception handling effectively in Apex and other programming languages.

Throwing vs. Catching Exceptions

What Does Throwing an Exception Do?

Throwing an exception signals that something went wrong in the program. It immediately halts execution and transfers control to an appropriate error-handling mechanism.

Example:

public void validateAmount(Integer amount) {
    if (amount <= 0) {
        throw new IllegalArgumentException('Amount must be greater than zero');
    }
    System.debug('Valid amount: ' + amount);
}

// Running validateAmount(0) will cause an unhandled exception

❌ If no try-catch is present, the program stops executing and throws an error.

What Does Catching an Exception Do?

Catching an exception prevents the program from crashing and allows for controlled recovery.

Example:

public void validateAmountWithHandling(Integer amount) {
    try {
        if (amount <= 0) {
            throw new IllegalArgumentException('Amount must be greater than zero');
        }
        System.debug('Valid amount: ' + amount);
    } catch (Exception e) {
        System.debug('Exception caught: ' + e.getMessage());
    }
}

✅ Execution continues, and instead of failing, an error message is logged.

Execution Flow of Try-Catch-Finally

How Does Try-Catch Work?

  1. Try Block: Code inside the try block executes first.
  2. Exception Thrown: If an error occurs, execution jumps to the catch block.
  3. Catch Block: Handles the error and prevents program termination.
  4. Finally Block (Optional): Executes whether an exception occurs or not.
  5. Remaining Code Execute normally.

Example:

public void tryCatchDemo(Integer amount) {
    try {
        System.debug('Trying to validate amount...');
        if (amount <= 0) {
            throw new IllegalArgumentException('Invalid amount');
        }
        System.debug('Amount is valid');
    } catch (Exception e) {
        System.debug('Exception caught: ' + e.getMessage());
    } finally {
        System.debug('Execution completed');
    }
}

Why Execution Doesn’t Stop in Try-Catch

The catch block prevents the program from crashing by handling the error. Without a try-catch, the program stops executing when an exception is thrown.

With Try-Catch:

Trying to validate amount...
Exception caught: Invalid amount
Execution completed

Without Try-Catch:

Trying to validate amount...
System.IllegalArgumentException: Invalid amount
Program execution stops here.

What Happens Without a Try-Catch?

  • The program stops immediately when an exception is thrown.
  • No further code execution occurs.
  • Users see an unhandled error, causing a bad experience.
  • Data operations (like saving records) may be left in an inconsistent state.

When to Use Finally?

The finally block always executes, whether an exception occurs or not. It is useful for cleanup operations like closing files, releasing resources, or logging information.

Example:

public void demoFinally() {
    try {
        System.debug('Executing try block');
        throw new IllegalArgumentException('Something went wrong');
    } catch (Exception e) {
        System.debug('Caught exception: ' + e.getMessage());
    } finally {
        System.debug('Cleanup actions in finally');
    }
}

Output:

Executing try block
Caught exception: Something went wrong
Cleanup actions in finally

Key Takeaways

  1. Throwing an exception stops execution unless it is caught.
  2. Catching an exception allows controlled handling and prevents crashes.
  3. Try-catch ensures execution continues even when errors occur.
  4. The finally block executes regardless of an exception occurring.
  5. Always use exception handling for better application stability and user experience.

Conclusion

Catching exceptions instead of simply throwing them ensures your application remains stable, user-friendly, and error-resilient. By using try-catch-finally properly, you can control execution flow, prevent abrupt failures, and implement recovery mechanisms. Whether in Apex, Java, or any other language, exception handling is a critical skill every developer should master.

Leave a Reply

Your email address will not be published. Required fields are marked *

About Me

As a Computer Engineering graduate, I have cultivated a diverse skill set in the field of IT over the past four years. My career began with a strong foundation in full-stack application development, which laid the groundwork for my subsequent expertise in artificial intelligence and Salesforce.

Services

Most Recent Posts

Featured Services

Essential Solutions for Salesforce Success

These featured services are the cornerstone of my offerings, designed to address the most critical needs of your business. Each service is crafted to deliver impactful results, ensuring you achieve your Salesforce objectives and drive success.

Salesforce Implementation & AI Integration

Seamless integration and configuration to get your Salesforce platform up and running effectively.

Customization & Development

Building custom solutions to align Salesforce with your unique business needs.

Data Migration & Integration

Securely transfer data and integrate with other systems to ensure a unified, accessible database.

Support and Maintenance

Comprehensive support and ongoing maintenance to keep your Salesforce system performing at its best.

Feedback

What People Think About Me

Your Partner in Salesforce Success

Unlock the full potential of your Salesforce environment by hiring a dedicated expert.

Abubakar Does Salesforce!

Services

Salesforce

Artificial Intellegence

Cloud Implementation

Administrator & Developer

Follow For Updates

© 2024