How to try-except an illegal matrix operation due to singularity in NumPy How to try-except an illegal matrix operation due to singularity in NumPy python python

How to try-except an illegal matrix operation due to singularity in NumPy


The syntax would be like this:

import numpy as nptry:    # your code that will (maybe) throwexcept np.linalg.LinAlgError as err:    if 'Singular matrix' in str(err):        # your error handling block    else:        raise


wim's answer no longer works for current versions of NumPy (I'm using 1.13 at the time of writing). Instead do:

import numpy as nptry:    # your code that will (maybe) throwexcept np.linalg.LinAlgError as e:    if 'Singular matrix' in str(e):        # your error handling block    else:        raise