Exception Handling in C#

Exception Handling in C#

In Programming Exception handling is used to generate custom errors, and prevents the program to crash. It provides a way to transfer control when some error occurs.  In this tutorial, you will learn Exception handling in C#. C# exception handling has four built-in keywords.

try: The main code is written in this block which we want to test. It can have more than one or one catch block to catch the exceptions.

catch: if is there some problem in try block like it will have some exception then the catch block catch it using its exception parameters.

finally: The finally block is used to execute a given set of statements, whether an exception is thrown or not thrown.

throw: A program throws an exception when a problem shows up. This is done using a throw keyword.

 

Syntax:

Exception Classes in C#:

            C# provides built-in exception classes. i.e. System.Exception, which is further divided into Application Exception (System.ApplicationException) and System Exception (System.SystemException) classes.
System Exception is used for predefined System generated exceptions whereas Application Exception is user defined exceptions.

1. Built-in Exceptions (System Exception):

System.IO.IOException

It handles the input or output exceptions or errors.

System.IndexOutOfRangeException

It handles the exceptions occurring when an array is filled up but user tries to input the values in it i.e. Array index out of bound.

System.ArrayTypeMismatchException

It handles the exceptions occurring when the user tries to input different type of value into an array of some other type. For instance, when the user enters String type values in an integer type array.

System.NullReferenceException

It handles the exceptions occurring when there is any kind of dereferencing of an object or null object.

System.DivideByZeroException

It handles the exceptions occurring when some value is divided by zero, which causes an infinite answer.

System.InvalidCastException

It handles the exceptions occurring at type-casting. Conversion of data types.

System.OutOfMemoryException

It handles the exceptions occurring when there is not enough free memory.

System.StackOverflowException

It handles the exceptions occurring when there is any scenario of stack overflow.

Exception handling Example

Now understand this concept with an example.

Exception Caught:

System.DivideByZeroException
System.DivideByZeroException

As we know divide with zero is an error so we control it using try catch block and show exception in output screen.

2. User-Defined Exceptions (Application Exception)

You can also define your own exceptions in C# by creating a class for custom exception and extend that class from Exception Class.

Example

 

Leave a Reply

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