Do you catch and re-throw exceptions properly?
Updated by Ben Neoh [SSW] 1 year ago. See history
catch {}catch (SomeException) {}catch { throw; }catch (SomeException) { throw; }
❌ Figure: Bad Example - Never use an empty catch block. Do something in the block or remove it.
catch (SomeException ex) { throw ex; }catch (SomeException ex) { someMethod(); throw ex; }
❌ Figure: Bad Example - Never re-throw exceptions by passing the original exception object. Wrap the exception or use throw.
Using throw ex
resets the stack trace, obscuring the original the error and may hide highly valuable information to debug this exception.
catch (SomeException){someMethod();throw;}
✅ Figure: Good Example - Calling throw
If you are following the Clean Architecture pattern - catching and rethrowing is useful for preventing your Infrastructure details from leaking into your Application e.g. we use a SQL server
catch (SqlException ex) when (ex.Number == 2601){throw new IdAlreadyTakenException(ex);}
✅ Figure: Good Example - By rethrowing a specific exception, my application code now doesn't need to know that there is a SQL database or the magic numbers that SQL exceptions use
Categories
Need help?
SSW Consulting has over 30 years of experience developing awesome software solutions.