Getsuyodev, Programming is mainly used when constructing an application. Programming requires knowledge of application domains, algorithms, and programming language expertise. Programming can be developed in different logic based on developer knowledge.

C# Exception handling



The C# language uses exceptions to handle errors and other exceptional events. Exceptions are the occurrence of some conditions that change the normal flow of execution. Exceptions have occurred in situations like your program run out of the memory; file does not exist in the given path, network connections are dropped etc. More specifically, for better understanding, we can say it as Runtime Errors occurs during the execution of a program that disrupts the normal flow of instructions.

C# Exception Handling – try-catch

C# Exception handling uses the try, catch, and finally keywords to attempt actions that may not succeed, to handle failures, and to clean up resources afterwards.

try
{
  //your code here
}
Catch (exception type)
{
  //your code here
}

finally

The code in the finally block will execute even if there are no Exceptions. That means if you write a finally block, the code should execute after the execution of try block or catch block.

try
{
  //your code here
}
Catch (exception type)
{
  //if the exception occurred
  //your code here
}
finally
{
  //your code here
}

The following example was trying to divide a number by zero.

try
{
    int val = 100;
    int div = 0;
    int resultVal;
    resultVal = (val / div);
    MessageBox.Show("The result is  : " + resultVal);
}
catch (System.Exception  ex)
{
    MessageBox.Show("Exception catch here - details  : " + ex.ToString());
}
finally
{
    MessageBox.Show("Enter finally block ");
}
using System;
using System.Windows.Forms;

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                int val = 100;
                int div = 0;
                int resultVal;
                resultVal = (val / div);
                MessageBox.Show("The result is  : " + resultVal);
            }
            catch (System.Exception  ex)
            {
                MessageBox.Show("Exception catch here - details  : " + ex.ToString());
            }
            finally
            {
                MessageBox.Show("Enter finally block ");
            }
        }
    }
}

When you execute this C# code the above source code, the program will throw a DividedByZero Exception, and after that, the control will go to finally clause.


Comments are closed.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More