C# try {} catch {}

后端 未结 11 2414
既然无缘
既然无缘 2021-02-08 10:51

hi and thanks for reading. im a newbie in programming and C# and sockets programming. in my code i try and catch problems to provide fault tolarence in my app. the following:

11条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-08 11:19

    You could but you would lose granularity and the ability to handle each issue individually, which isn't the best practice. Usually you would handle different types of exceptions first, just as you have, then if you need to do something with any unhandled exceptions you could add the Exception at the end. Re-throw it once you're done to preserve the stack-trace and let it bubble up.

    Keep what you have an add a base case at the end:

    catch (ArgumentNullException e) { ... }
    catch (EncoderFallbackException e)  { ... }
    catch (SocketException e) { ... }
    catch (ArgumentOutOfRangeException e)  { ... }
    catch (ObjectDisposedException e) { ... }
    catch (Exception e)
    {
        // not handled by above exceptions, do something if needed
        throw; // after doing what you need, re-throw it
    }
    

提交回复
热议问题