+ Start a Discussion
Ken_KoellnerKen_Koellner 

Catching LimitException on batch apex executeBatch.

I writing a page that lets a user submit a certain batch apex task.  I want to get the exception where the limit of 5 queued/running jobs is exceeded so I can put up a message tell the user to try again later.

 

I tried running the sample code below as ad-hoc apex to test the catch.  It compiles but the exception is not caught.  Am I not catching the correct Exception?

 

 

KenTestBatchable ktb ;

for (integer i=0; i<7; i++) {
  try {
    ktb = new KenTestBatchable('1000');
    Database.executeBatch(ktb);
  } catch(LimitException ex) {
	system.debug ('xyzzy ' + ex.getMessage());
  }
}

 

 

Ken_KoellnerKen_Koellner

I tried this also.  It appears there's not way to catch this exception.

 

There's no Limits methods to check the available apex jobs.  I guess you have to query AsyncApexJob and see if there are five jobs already there.

 

 

KenTestBatchable ktb ;

for (integer i=0; i<7; i++) {
  try {
    ktb = new KenTestBatchable('1000');
    Database.executeBatch(ktb);
  } catch(LimitException ex) {
	system.debug ('xyzzy limit exception ' + ex.getMessage());
  }
  catch(Exception ex) {
	system.debug ('xyzzy other exception ' + ex.getMessage());
  }
}

 

 

Ken_KoellnerKen_Koellner

I figure I could run the query --

 select count()from AsyncApexJob where status in [‘Processing’,’Queued’];

and not submit if unless a number < 5 is returned.

 

Of cource there would be a small window where another job could sneak in prior to mine being submitted but that's pretty unlikely.