Exceptions and handling exceptions in code

Exceptions are types that are derived from the System.Exception class. We use the try block around statements that may throw an exception. When an exception occurs, control jumps to the catch statement, where CLR collects all the required stack trace information before terminating the program and displaying a message to the user. If exception handling is not done, the program just terminates with an error. While handling exceptions, it is important to understand that if we cannot handle an exception, we should not catch it. This ensures that the application will be in a known state. When you define a catch block, you define an exception variable that can be used to obtain more information, such as the origin of the exception, which line in the code threw this exception, the type of exception, and so on.

A programmer can create and throw exceptions from the application logic using the throw keyword. Each try block may or may not define the finally block, which will be executed whether an exception is thrown or not. This block helps us release resources that have been used in the code block. Alternatively, if you want a piece of code to execute in all scenarios, it can be placed in the finally block.

In the upcoming sections, we will look at how we can use exceptions, the syntax of the try-catch-finally block, using the finally block, when we can dispose of unused objects, different types of system exceptions, and creating our own exceptions.

..................Content has been hidden....................

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