improved exception handling to avoid segfaults