top of page
Writer's pictureThe Tech Platform

Exception Handling in C#

Exception Handling in C# is a process to handle runtime errors. We perform exception handling so that normal flow of the application can be maintained even after runtime errors. In C#, exception is an event or object which is thrown at runtime. All exceptions the derived from System.


Benefits of Exception Handling in C# is as follow:

(a) Exception handling can control run tune errors that occur in the program.

(b) It can avoid abnormal termination of the program and also shows the behavior of program to users.

(c) It can separate the error handling code and normal code by using try-catch block.


Exception Classes in C#

C# exceptions are represented by classes. The exception classes in C# are mainly directly or indirectly derived from the System.Exception class. Some of the exception classes derived from the System.Exception class are the System.ApplicationException and System.SystemException classes.

The System.ApplicationException class supports exceptions generated by application programs. Hence the exceptions defined by the programmers should derive from this class.


The System.SystemException class is the base class for all predefined system exception.


The following table provides some of the predefined exception classes derived from the Sytem.SystemException class āˆ’




Exception Class Description


1. System.IO.IOException Handles I/O errors.


2. System.IndexOutOfRangeException Handles errors generated when a method refers to an array

index out of range.


3. System.ArrayTypeMismatchException Handles errors generated when type is mismatched with the

array type.


4. System.NullReferenceException Handles errors generated from referencing a null object.


5. System.DivideByZeroException Handles errors generated from dividing a dividend with zero.


6. System.InvalidCastException Handles errors generated during typecasting.


7. System.OutOfMemoryException Handles errors generated from insufficient free memory.


8. System.StackOverflowException Handles errors generated from stack overflow.



Syntax:

try
{
    // put the code here that may raise exceptions
}
catch
{
    // handle exception here
}
finally
{
    // final cleanup code
}

try block: Any suspected code that may raise exceptions should be put inside a try{ } block. During the execution, if an exception occurs, the flow of the control jumps to the first matching catch block.


catch block: The catch block is an exception handler block where you can perform some action such as logging and auditing an exception. The catch block takes a parameter of an exception type using which you can get the details of an exception.


finally block: The finally block will always be executed whether an exception raised or not. Usually, a finally block should be used to release resources, e.g., to close any stream or file objects that were opened in the try block.



Example: Exception Handling using try-catch block

public class Program
{
	public static void Main()
	{
		try
        {
            Console.WriteLine("Enter a number: ");

            var num = int.Parse(Console.ReadLine());

           Console.WriteLine("Squre of {0} is {1}", num, num * num);
        }
        catch
        {
            Console.WriteLine("Error occurred.");
        }
       
	}
	
}

Output:


Creating User-Defined Exceptions

You can also define your own exception. User-defined exception classes are derived from the Exception class. The following example demonstrates this āˆ’

using System;

namespace UserDefinedException 
{
    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);
        }
    }
}

Output:




The Tech Platform

0 comments

Comments


bottom of page