Performing DML operations directly in catch blocks creates a dangerous situation where the original exception can be completely masked.
When your code encounters an exception, the catch block is meant to handle that error gracefully. However, if you perform a DML operation (like
inserting an exception log record) within the catch block, that DML operation can itself fail for various reasons:
- Missing required fields
- Validation rule failures
- Governor limit violations
- Field-level security restrictions
When the DML operation fails, it throws a new DmlException that replaces the original exception. This means you lose all information
about what actually went wrong in your business logic. Instead of seeing "Account validation failed: Industry is required", you might only see
"Exception logging failed: Missing required field Exception_Type__c".
This makes debugging extremely difficult and can hide critical issues in your application. The original problem remains unfixed while you chase
secondary logging failures.
What is the potential impact?
The primary risk is loss of critical debugging information. When the original exception is masked, developers cannot identify and fix the root
cause of failures.
This can lead to:
- Prolonged system issues that remain unresolved
- Increased debugging time and development costs
- Poor user experience due to unaddressed underlying problems
- Potential data integrity issues if business logic failures go unnoticed