better merging function with exception handling