How to use C# exceptions statements
The C# language uses exceptions to handle errors and other exceptional events. Exceptions are the occurrence of some conditions that changes the normal flow of execution . Exceptions are 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
In .NET languages , Structured Exceptions handling is a fundamental part of Common Language Runtime . All exceptions in the Common Language Runtime are derived from a single base class , also you can create your own custom exception classes. You can create an exception class that inherits from Exception class . Creating an exception object and handing it to the runtime system is called throwing an exception.
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 is 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
}
From the following CSharp code , you can understand how to use try..catch statements. Here we are going to divide a number by zero .
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 wil go to finally clause.
|