Exception is an error that occurs at compile time or run time.
Compile time error occurs at compile time due to syntax errors
Runtime error that occurs during the execution of Program. This errors are because of improper logics in the code.
.NET Runtime environment terminates the program execution when an exception occurs.

Exception handling is an in built mechanism in .NET framework to detect and handle run time errors.
In C# Exception Handling is managed using the following keywords

  • try
  • catch
  • finally
  • throw

try

Code that may cause exception is handled in try block.
If exception occurs, control transfers to catch block.
If no exception found then control transfers to finally block.

Note
After try block you can use multiple catch blocks.

catch

If an exception occurs in try block , immediately the control transfers from try block to catch block to handle the exception.
If no exception found in try block, then catch will not executes.

finally

Any code within the finally block must be executed in all cases. finally block doesn’t bother about whether exceptions occurs or not.

Mostly finally block is used to release the resources that stored in an object or a variable.

For example , if you open a SQL connection for performing DML operations(update,insert ,select). then you must close the connection whether exception occurred or not. during the execution of DML operations.

throw

To manually throw an exception, we use the keyword throw.

syntax for try-catch-finally

try
{
}
catch(ExceptionType1 ex)
{
}
catch(ExceptionType2 ex)
{
}
fianlly
{
}

C# simple Program to handle division operation using try catch blocks

C# code

 /*
 * In this program we caught an exception
 * i.e. Arithmetic Exception which occurred 
 * due to 0 in denominator place.
 */
    public class Exceptions
    {

        public static void Main(String[] args) {
 
		try 
                 {
 
			int a = 20;
			int b = 0;
			// ArithmeticException: / by zero
			int div = a / b;
			
			Console.WriteLine("Div= " + div);
			
		} 
               catch (ArithmeticException e) 
                {

                 Console.WriteLine(e); 
		}
	}

    }

Output
System.DivideByZeroException: Attempted to divide by zero.
at Try_catch.Exceptions.Main(String[] args) in e:\PRACTICECODEFORALLDOTNETBAS
ICS\MASTERPROJECT\Try catch\Try catch\Program.cs:line 21

Related Posts