Improve exception safety

Introduce raii_wrapper to perform finalizing surely.