There are two operators used in c# to handle the overflow exception control as given below.
C# provides the checked and Unchecked operators.If we use checked operator in codes, the CLR will enforce overflow checking and throw an exception if an overflow occurs. Example:-
Output :-OverflowException was Unhandled- Checked Operator
- Unchecked Operator
C# provides the checked and Unchecked operators.If we use checked operator in codes, the CLR will enforce overflow checking and throw an exception if an overflow occurs. Example:-
private void button1_Click(object sender, EventArgs e)
{
byte m = 255;
checked
{
m++;
}
MessageBox.Show(m.ToString());
}
If we run this codes then we will get an error message. I will show it later.
Note :-
The Byte data type can only hold values in the range 0 to 255 ,so incrementing the value of m causes an overflow.
1.) UnChecked Operator :-
If we want to suppress overflow checking, we can use Unchecked operator.In this case, no exception will be raised,but we will lose our data.We already know that ,the byte type can't hold a value of greater than 255.So the overflow bits will be discarded.Variable m hold a value of zero.
Example:-
private void button2_Click(object sender, EventArgs e)
{
byte m = 255;
unchecked
{
m++;
}
MessageBox.Show("m=" +m.ToString());
}
Output :- m=0
There are some steps to implement this whole concepts as given below:-
Step 1:- First open your visual studio --> File -->New -->Project -->Select WindowsFormsApplication --> OK.
Step 2:- Now drag and drop two button on the page from the toolbox as shown below:-
Step 3:- Now Double click on each button (Checked & Unchecked) and write the c# codes as given below:-
using System;
using System.Windows.Forms;
namespace checked_operaors
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
byte m = 255;
checked
{
m++;
}
MessageBox.Show(m.ToString());
}
private void button2_Click(object sender, EventArgs e)
{
byte m = 255;
unchecked
{
m++;
}
MessageBox.Show("m=" +m.ToString());
}
}
}
Step 4:- Now Run the application --> Press press Checked Button --> You will get an error message as shown below:-Step 5:- Now press Unchecked button --> You will value of m=0.It means you lose the values.
Note:-Whenever there is a risk of an unintentional overflow ,we really need some way of making sure that we get the result as we want.
Download Whole Application
Download
For More...
Benefited alot from your tutorial...good job.pls can u post tutorials on entity framework
ReplyDelete