Exceptions are a type of error that occurs during the execution of an
application.Exceptions allow an application to transfer control from one part
of the code to another. When an exception is thrown, the current flow of the
code is interrupted and handed back to a parent try catch block. C# exception
handling is done with the follow keywords: try, catch, finally, and throw
try –
A try block is used to encapsulate a region of code. If any code throws an
exception within that try block, the exception will be handled by the
corresponding catch.
catch –
When an exception occurs, the Catch block of code is executed. This is where
you are able to handle the exception, log it, or ignore it.
finally –
The finally block allows you to execute certain code if an exception is thrown
or not. For example, disposing of an object that must be disposed of.
throw –
The throw keyword is used to actually create a new exception that is the
bubbled up to a try catch finally block.
User-defined
exception classes are derived from the Exception class.
.NET provides a hierarchy of exception classes ultimately derived from
the base class Exception. However, if none of the predefined exceptions meets
your needs, you can create your own exception classes by deriving from the
Exception class
Example :
|
using System;
using System.Collections;
using
System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class TestTemperature
{
static void Main(string[] args)
{
Temperature temp = new Temperature();
try
{
temp.showTemp();
}
catch (TempIsZeroException e)
{
Console.WriteLine("TempIsZeroException: {0}", e.Message);
}
Console.ReadKey();
}
}
}
public class TempIsZeroException : Exception
{
public TempIsZeroException(string message) : base(message)
{
}
}
public class Temperature
{
int temperature = 0;
public void showTemp()
{
if (temperature == 0)
{
throw (new TempIsZeroException("Zero Temperature
found"));
}
else
{
Console.WriteLine("Temperature: {0}", temperature);
}
}
}
|