Try catch - Exception handling
//The Exception family includes a wide variety of exceptions, many of which are intend-ed for use by various parts of the .NET Framework
try
{
int leftHandSide = int.Parse(lhsOperand.Text);
int rightHandSide = int.Parse(rhsOperand.Text);
int answer = doCalculation(leftHandSide, rightHandSide);
result.Text = answer.ToString();
}
catch (Exception ex) // this is a general catch handler
{
//...
}
//You can throw an exception by using the throw statement
public static string monthName(int month)
{
switch (month)
{
case 1 :
return “January”;
case 2 :
return “February”;
...
case 12 :
return “December”;
default :
throw new ArgumentOutOfRangeException(“Bad month”);
}
}
//example 2
if(int == null)
{
throw new nullException("invalid number");
}
//A checked statement is a block preceded by the checked keyword. All integer arithmetic in a checked statement always throws an OverflowException
int number = int.MaxValue;
checked
{
int willThrow = number++;
Console.WriteLine(“this won’t be reached”);
}
//use the unchecked keyword to create an unchecked block statement. All integer arithmetic in an unchecked block is not checked and never throws an OverflowException
int number = int.MaxValue;
unchecked
{
int wontThrow = number++;
Console.WriteLine(“this will be reached”);
}
//A finally block occurs immediately after a try block or immediately after the last catch handler after a try block
//As long as the program enters the try block associated with a finally block, the finally block will always be run
try
{
string line = reader.ReadLine();
while (line != null)
{
...
line = reader.ReadLine();
}
}
finally
{
if (reader != null)
{
reader.Dispose();
}
}
try
{
int leftHandSide = int.Parse(lhsOperand.Text);
int rightHandSide = int.Parse(rhsOperand.Text);
int answer = doCalculation(leftHandSide, rightHandSide);
result.Text = answer.ToString();
}
catch (FormatException fEx)
{
//...
}
catch (OverflowException oEx)
{
//...
}
try
{
int leftHandSide = int.Parse(lhsOperand.Text);
int rightHandSide = int.Parse(rhsOperand.Text);
int answer = doCalculation(leftHandSide, rightHandSide);
result.Text = answer.ToString();
}
catch (FormatException fEx)
{
// Handle the exception
...
}
//If, after cascading back through the list of calling methods, the runtime is unable to find a matching catch handler, the program terminates with an unhandled exception.