An attempt to invert the transformation matrix with the inverted() method can be failed if, for example, some constraint affects the object for which the initial matrix is calculated.
In this case, Blender will generate an error:
ValueError: Matrix.invert(ed): matrix does not have an inverse
In order to avoid an error, to invert such matrices, you need to use the inverted_safe() method
from mathutils import Matrix
transform_matrix = Matrix()