I have a simple after insert trigger which inserts a task when an account is created. I am struggling to cover the catch statement in my test class. Is there a way to cover it?

Apex Trigger

trigger Account on Account (after insert) {

Apex Class

public class AccountTriggerClass {
    public static void taskInsert(List<Account> acc)
            List<Task> taskList = new List<Task>();
            for(Account a : acc){
                Task tk = new Task();
                tk.Subject = 'New Task created by after insert';
                tk.WhatId = a.Id;
            Database.insert(taskList, false);
        catch(exception ex){

Test Class

public class AccountTriggerClassTest {
    @isTest private static void taskInsertMethod(){
        Account a = new Account();
        a.Name = 'Test Account 2';
        insert a;

Catch not covered: enter image description here

  • what's the point of that catch statement? Database.insert returns a Database.SaveResult[] that would contain success or error messages for each record attempted to be inserted. Doc. See also existing answers about blindly catching general exceptions. Typically, you'd catch an exception with a purpose/scenario in mind which makes testing it easier. Dec 31, 2020 at 1:35
  • See also this question about 100% coverage.
    – sfdcfox
    Dec 31, 2020 at 2:51

1 Answer 1


Aside from the fact you are just writing to debug on an exception which is not best practice ... nor do you have any asserts (also not best practice) you are using a partial success pattern that will not throw a DMLException

Database.insert(taskList, false);

which is normally coded as:

Database.SaveResult[] results = Database.insert(tasklist,false);
for (Database.SaveResult result : results) {
    if (!result.isSuccess()) { do something useful like log to an sobject the errors for later investigation}

Otherwise, given that you are creating valid Task objects, you'll never be able to get an exception without catering your test to validation rules on Task.

Trust me, trying to get 100% code coverage for every exception catch block is a fool's errand - especially if you use some standard exception handling that you reuse over and over.

If you want to learn more about sophisticated strategies for mocking exceptions in service layer classes, check out ApexMocks and the doThrowWhen method in this GitHub repo .. but I suspect this is far more than you want to bite off for the example above.

  • Thank you this is helpful. I think there is no need of try catch statement in the first place. Dec 31, 2020 at 1:44

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .