Exception Handling In C# With Programming Examples

Before starting to learn about Exception handling, it is required to know what actually Exception is and why it is required to learn exception handling. Exception means for programming error which appears at runtime. For example you have create a program in which user inputs two numbers and program divide the number and show output. Now consider what happen if user input zero as a second or first number. As we all know that any number divided by zero returns infinite. In this condition your program breaks unconditionally by showing DivideByZeroException. To handle any runtime error you must keep your code under exception handling block.

Exception Handling is a way to control runtime programming error in a structured and controlled manner. If any runtime error visible the handler shows easy readable message telling user what the problem is and continue the program.

How to handle Exception at runtime?

All the exception handling is based on only four keywords: try, catch, throw and finally. All Exception class is derived from System.Exception namespace.

try: try keyword is used for identifying code block which may cause exception at runtime.

catch: catch keyword handle the exception if try block through exception. The code under try block if raises runtime error, try block sends handler to catch block to handle error.

throw: throw keyword is used for creating user defined exception messages.

finally: finally block executed when exception is raised or not. It is used for removing resource and executing set of code.

Leave a Reply

Your email address will not be published. Required fields are marked *