Exception Handling in C# with programming Examples

In this Section you will learn:
  • What is Exception?
  • How to handle various types of exception
  • Various types of common exception messages

What is Exception?

Before starting to learn Exception handling, it is necessary to know what actually Exception is and why it is necessary to learn exception handling. Exception stands for programming error which appears at runtime. For example, you have made a program in which user inputs two numbers and program divide the number and show output. Now consider what happens if user input zeroes 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.

 

Demo Image

Exception Image

Exception Handling gives a way to control runtime programming error in a structured and controlled manner. If any runtime error appears 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 raises 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 whether exception is raised or not. It is used for cleaning resource and executing set of code.

Exception Handling

List of Contents

Summary

In this chapter, only basic overview of exception handling is explained. In the next chapter you will learn it with easy language and understandable programming example. In the next chapter you will learn try catch finally block.

 

Share your thought