Rolled back inserted record from table1 if record insertion fail in table2 in D365FO or AX2012
You need to use a concept called database transactions.
If you run several database operations (e.g. inserts or updates) in a single transaction, they're considered a single operation that must either succeed or, in case of a failure, all changes must be rolled back.
In your case, you can do something like this:
Table1 t1;
Table2 t2;
ttsbegin;
... populate fields...
t1.insert();
t2.insert();
ttscommit;
The statements between ttsbegin and ttscommit form a single transaction. If an exception is thrown anywhere in the block, all database changes are automatically rolled back.
This is a super-important topic, because if you don't use transactions correctly, you may cause data inconsistencies in your (your client's) production database, potentially with serious consequences.