Basics of exception handling

Exception handling in C# is mainly achieved by four keywords: try, catch, throw, and finally. Later, we will talk about these keywords in detail. However, just to give you a basic idea of what is meant by those keywords, let's briefly discuss them:

  • try: When you are not sure of the expected behavior of a piece of code or if there is a possibility of an exception, you should put that code in a try block. The try block will throw an exception if any exception happens inside the code for that block. If no exception occurs, the try block will act like a normal code block. The try block is actually designed to throw exceptions, which is its main task.
  • catch: The catch block is executed when an exception is caught. Exceptions thrown by the try block will be handled by the following catch block. There could be multiple catch blocks for a try block. Each catch block can be dedicated to a particular exception. Consequently, we should write different catch blocks for different types of exception.
  • throw: This is used when you manually want to throw an exception. There could be situations in which you want to do this to control a specific kind of situation.
  • finally: This is a block of code that will be compulsorily executed. It doesn't matter whether the try block threw an exception or not, the finally block will be executed. This is mainly used to code some tasks that are essential to handle in any case.
..................Content has been hidden....................

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