.net - Are nested Try/Catch blocks a bad idea? -
let's have structure so:
try ' outer try code, can fail more generic conditions, ' know less , might not able handle try ' inner try code, can fail more specific conditions, ' know more about, , handle appropriately catch innerex exception ' handle inner exception end try catch outerex exception ' handle outer exception end try
i have seen opinions nesting try
blocks discouraged, not find specific reasons.
is bad code? if so, why?
there circumstances they're idea, e.g. 1 try/catch whole method , inside loop want handle exception , continue processing rest of collection.
really reason if want skip bit errored , carry on, instead of unwinding stack , losing context. opening multiple files in editor example.
that said, exceptions should - exceptional. program should handle them try avoid them part of normal execution flow. they're computationally expensive in most languages (python being notable exception).
one other technique can useful catching specific exception types...
try 'some code read file catch ex ioexception 'handle file access issues (possibly silently depending on usage) catch ex exception ' handle other exceptions. ' if you've got handler further up, omit catch , let ' exception propagate throw end try
as pointed out gooch in comments below, use nested try/catches in our error handling routines...
try try 'log database catch ex exception 'do nothing end try try 'log file catch ex exception 'do nothing end try catch ex exception 'give , go home end try
Comments
Post a Comment