Using the finally block
The finally
block in Apex provides a block of code that is guaranteed to execute. The primary use case of the finally
block is to ensure that any changes we do not want to persist are rolled back or that the code can continue past the error. It can also be used to end the transaction should a piece of code fail and you wish to end the process.
In the following example code, we are creating a Savepoint
before inserting a new account and then attempting to insert a new related contact:
Savepoint entryState = new Database.setSavepoint(); try { insert acc; //insert our populated account variable } catch(DMLException accEx) { //handle the DML Exception return; } con.AccountId = acc.Id; try { insert con; } catch(DMLException conEx) { //Handle the DML Exception } finally { if(con.Id == null) { ...