c# - Try-catch handler and DivideByZeroException -
i have function ,that calculate numbers , catch exceptions:
try{ .... return maincount /count; } catch (dividebyzeroexception ex) { return 0; } catch (exception ex) { return 0; }
so, catch right? or may program should crash?
thank you!
never catch exception
(base class) without throw: means "whatever had happened return zero". it's not desired behaviour in case, say, of internal .net error or ram corruption...
try { ... return maincount / count; } catch (dividebyzeroexception) { // <- don't need instance ("ex") here // quite ok: return 0 when count == 0 return 0; }
better practice, however, test if count == 0
:
return count == 0 ? 0 : maincount / count;
typical pattern exception
catch
try { ... } catch (exception e) { // whatever had happend, write error log savetolog(e, ...); // , throw exception again throw; // <- not "throw e;"! }
Comments
Post a Comment