Exception Handling in C#

C# Exception handling is a mechanism in .NET to detect and handle run time errors.

The try… Catch block is used to implement exception handling in C#

C# provides three keywords try, catch and finally to implement exception handling.

The try encloses the statements that might throw an exception whereas catch handles an exception if one exists. The finally can be used for any cleanup work that needs to be done.

Syntax for Exception Handling as below:

try
 {
 //Statement which can cause an exception.
 } catch(ExceptionType) {
 //Statements for handling the exception
 } finally {
 //Any cleanup code
 }

Demo For Exception Handling as below:

namespace ExceptionHandling
{
    class program
    {
        static void Main(string[] args)
        {
            try
            {
                int a = 90;
                int b = 0;
                int c = a / b;
                Console.WriteLine("Ans: " + c);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex.Message);
            }
            finally
            {
                Console.ReadLine();
            }
        }
    }
}

Output :

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories