correctly handle exception in Python3