Exception handling best practices

As you can see, there are different ways in which you can handle exceptions: sometimes you can throw exceptions, sometimes you can use the finally block, sometimes you can use multiple catch blocks. Consequently, there is a chance that you can get confused at the beginning if you don't have enough experience with exception handling. But thanks to the C# community, there are some best practices for exception handling. Let's have a look at some of them:

  • Use a finally block to close/clean up dependent resources that could cause a problem in the future.
  • Catch the specific exception and handle it properly. Use multiple catch blocks if needed.
  • Create your own exceptions if needed and use them.
  • Handle exceptions as soon as possible.
  • Don't use a general exception handler if you can handle an exception using a specific handler.
  • The exception messages should be very clear.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.69.53