C# Error handling catch blocks -



C# Error handling catch blocks -

why adviced of time should not trap errors "exception" trap errors expect developers. there performance nail in trapping generic errors or recommended best practice point of view?

seek { // } catch(exception e) { //log error }

the best practice grab specific exception first , move on more generic ones.

exception handling (c# programming guide)

multiple grab blocks different exception filters can chained together. grab blocks evaluated top bottom in code, 1 grab block executed each exception thrown. first grab block specifies exact type or base of operations class of thrown exception executed. if no grab block specifies matching exception filter, grab block not have filter selected, if 1 nowadays in statement. it of import position grab blocks specific (that is, derived) exception types first.

for question:

why adviced of time should not trap errors "exception" trap errors expect developers.

an illustration grab nullreferenceexception. never improve practice grab nullreferenceexception, instead 1 should check object beingness null before using instance members. illustration in case of string.

string str = null; seek { console.writeline(str.length) } catch(nullreferenceexception ne) { //exception handling. }

instead check should in place checking against null.

if(str != null) console.writeline(str.length);

edit:

i think got question wrong, if asking exception should caught , shouldn't imo, exceptions can dealt should caught , rest should left in library can bubble upper layer appropriate handling done. illustration violation of primary key constraint. if application taking input(including primary key) user , date beingness inserted database, exception can caught , message can shown user "record exists" , allow user come in different value.

but if exception related foreign key constraint (e.g. value dropdown list considered invalid foreign key) exception should bubble , generic exception handler should log in appropriate place.

for illustration in asp.net applications, these exception can logged in application_error event , general error page can shown user.

edit 2: op's comment:

if @ low level if there performance degeradation in catching generic error inspite of knowing if error sqlexception

even if there going performance difference should negligible. grab specific exception, if know exception going sqlexception grab that.

c#

Comments

Popular posts from this blog

web services - java.lang.NoClassDefFoundError: Could not initialize class net.sf.cglib.proxy.Enhancer -

Accessing MATLAB's unicode strings from C -

javascript - mongodb won't find my schema method in nested container -