C# Exception Handling - User-Defied Exceptions

    1 Votes

An exception is a problem which arises during the execution of the program. The exception handling helps us to deal with an unexpected or expected problem which arises while program is running. It uses the try, catch, finally and throw keyword.

  • try: In the try block there is a block of code which is activated for the particular exceptions. The try block is followed by one or more catch blocks.
  • catch: In this the program catches the exception with an exception handler in a program where we want to handle the problem. It indicates the catching of an exception.
  • finally: In this it is used to execute the given set of statements where either exception is thrown or not. For example: if we open a file it must be closed where exception is raised or not.
  • throw: In this the program throws an exception when the problem is raised up and throw keyword is used for solving this problem.

 

Let us have an example to understand it:
using System;
namespace ConsoleApplication1
{
   class Program
   {
      int res;
      Program()
      {
         res = 0;
      }
      public void division(int num1, int num2)
      {
         try
         {
            res = num1 / num2;
         }
         catch (DivideByZeroException e)
         {
            Console.WriteLine("The exception caught: {0}", e);
         }
         finally
         {
            Console.WriteLine("The result is: {0}", res);
         }
      }
      static void Main(string[] args)
      {
         Program d = new Program();
         d.division(2, 0);
         Console.ReadKey();
      }
   }
}
Output:

The exception caught: System.DivideByZeroException: Division by zero at ConsoleApplication1.Program.division (Int32 num1, Int32 num2) [0x00000] in <filename unknown>:0 . The result is: 0

User-defined exception

In the user defined exception we can define our own exception. In the user defined exception classes are derived from the exception class. Let us have an example:

using System;
namespace UserDefinedException
{
   class NumberTest
   {
      static void Main(string[] args)
      {
         Number n = new Number();
         try
         {
            n.showNum();
         }
         catch(NumIsZeroException e)
         {
            Console.WriteLine("NumIsZeroException: {0}", e.Message);
         }
         Console.ReadKey();
      }
   }
}

public class NumIsZeroException: Exception
{
   public NumIsZeroException(string message): base(message)
   {
   }
}

public class Number
{
   int num = 0;
   public void showNum()
   {
      if(num == 0)
      {
         throw (new NumIsZeroException("Zero number found.."));
      }
      else
      {
         Console.WriteLine("Number is: {0}", num);
      }
   }
}

Output:

NumIsZeroException: Zero number found..

Exception Classes

In C# exceptions are represented through classes. The exception classes in C# can be derived directly or indirectly from the System.Exception class. Some of the classes derived from System.Exception are:

  • System.ApplicationException
  • System.SystemException

Here given below is the table of predefined exception classes which are derived from System.SystemException:

Exception ClassDescription
System.IO.IOException It handles the input-output errors.
System.IndexOutOfRangeException It handles the errors generated when the method refers to an array index out of range.
System.ArrayTypeMismatchException It handles the errors generated when the type is mismatched with the array type.
System.NullReferenceException It handles the errors generated from dereference a null object reference.
System.DivideByZeroException It handles the errors generated from dividing a dividend with zero.
System.InvalidCastException It handles the errors generated during typecasting.
System.OutOfMemoryException It handles the errors generated from insufficient free memory.
Planning to do an MBA?
A quick all-in-one MBA entry manual for MBA Aspirants. Book covers
  • Possible MBA Tests & Exam Preparation
  • Tips to choose right MBA Program
  • Essay, Resume & Letter of Recommendation
  • MBA Interview Preparation
  • MBA Financial Planning
Price - 6.99$
 

Popular Videos

How to speak to people

How to speak so that people want to listen.

Got a tip or Question?
Let us know

Related Articles

C# Overview & Evolution of C# Language
Introduction of .NET Framework
C# Datatypes - Datatype Conversion, Boxing & Unboxing
C# Metadata, Metadata Tables and Benefits
C# - Common Language Intermediate (CIL)
C# - Class and Objects
C# Assembly - How to create and share assembly
C# Garbage Collection
C# Indexers
C# Inheritance - Single, Hierarchical, Multilevel & Multiple Inheritance
C# Polymorphism - Static and Dynamic polymorphism
C# Abstract Classes
C# Structures
C# Delegates and Events
C# Collections
C# XML Read and Write
C# Windows Presentation Foundation (WPF)
Language Integrated Query (LINQ)