In C#, there are many instances where errors occuring in programming but in few exceptional cases some errors might not be caught this situation is called as Exceptions. To control this exception a technique called Exception Handling is used.
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.
Common Exceptions
Exceptions
System.SystemException class is the base class for all predefined system exception.
try block is where code is written which can throw an exception.Single try can have multiple catch Object.
Catch block is use to handle the exception thrown from try block.
Finally block is used to execute statement, which need to execute compulsory whether exception occurs or not.
Throws keyword catch exception when program throw an exception.
Conceptual
figure
Syntax
try
{
//Code Here
}
Catch
{
//Code Here
}
Finally
{
//Code Here
}
Example
[csharp]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SPLessons
{
class Program
{
static void Main(string[] args)
{
try
{
Console.WriteLine("Welcome to SPLessons Calculator");
int a=1,b=0,c=0;
c=a/b;
Console.WriteLine("Divide:"+c);
}
catch(DivideByZeroException d)
{
Console.WriteLine(d.Message);
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
finally
{
Console.WriteLine("Thank you for using SPLessons");
}
}
}
[/csharp]
Output: