Modify code to catch exceptions