Proper resource cleanup even when errors