• Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
  • Skip to footer

Computer Notes

Library
    • Computer Fundamental
    • Computer Memory
    • DBMS Tutorial
    • Operating System
    • Computer Networking
    • C Programming
    • C++ Programming
    • Java Programming
    • C# Programming
    • SQL Tutorial
    • Management Tutorial
    • Computer Graphics
    • Compiler Design
    • Style Sheet
    • JavaScript Tutorial
    • Html Tutorial
    • Wordpress Tutorial
    • Python Tutorial
    • PHP Tutorial
    • JSP Tutorial
    • AngularJS Tutorial
    • Data Structures
    • E Commerce Tutorial
    • Visual Basic
    • Structs2 Tutorial
    • Digital Electronics
    • Internet Terms
    • Servlet Tutorial
    • Software Engineering
    • Interviews Questions
    • Basic Terms
    • Troubleshooting
Menu

Header Right

Home » C# » Libraries » Exception Handling in C#
Next →
← Prev

Exception Handling in C#

By Dinesh Thakur

There are no exceptions in C arid in C++ one can get away from using them with error handling functions such as exit() and terminate(). In C# these functions are absent and we introduce exceptions which take their place. The exception handling in C#, and Java is quite similar.

When a program has a bug we can intercept it in the flow of execution by inserting an error handling statement. To catch a particular type of exception in· a piece of code, you have to first wrap it in a ‘try’ block and then specify a ‘catch’ block matching that type of exception. When an exception occurs in code within the ‘try’ block, the code execution moves to the end of the try box and looks for an. appropriate exception handler. For instance, the following piece of code demonstrates catching an exception specifically generated by division by zero:

try

{

int zero = 0;

res = (num/ zero);

}

catch (system.dvideByzeroException e)

.{

Console.writeLine(“Error: an attempt to divide by zero”);

}

You can specify multiple catch blocks (following .each other), to catch different types of exception. A complication results, .however, from the fact that exceptions form an object hierarchy, so a particular exception might match more than one catch box. What you have to do here is put catch boxes for the more specific exceptions before those for the more general exceptions. At most one catch box will be triggered by an exception, and this will be the first (and thus more specific) catch box reached.

For example, program, which does not, accesses the first element of an array. Then, during some array handling operations, if an access to array[O] is attempted, the’ OutOfRange exception is thrown. class OutOfRange is an exception class. ‘Allexception classes inherit from Exception class. Compiler, will give an error if the inheritance from, the Exception class is not made .

In the code that follows we throw an exception OutOfRange if i == 0 is true. The try statement is enclosing the part of the code where the exception is expected. If the exception occurs it is handled by the code inside the catch statement. The catch statement takes as an argument an instance of class System.Exception.

Exception Handling Program

 

using system;

class OutOfRange:Exception

{

}

class Demo

{

int n;

public int []array;

public Demo ( int n)

{

this.array = new int[n];

this.n = n;

}

public void show_element (int i)

{

try

{

if (i == 0) throw ( new OutOfRange());

catch (Exception e)

{

console.writeLine(“Exception :{0}”,e);

}

console.WriteLine (array [i]);

}

}

class Test

{

public static void Main()

{

Demo test = new Demo (3);.

test.array [1] = 2;

test.array [2] = 3;

test.show_element (0);

}

}

 

OUTPUT:

 

Exception: OutOfRange: An exception of type outOfRange was thrown. at Demo.show_element(Int32 i) in

Go:\cSharpEd\excep.cs:line 19

 

The above program can be simplified if you use a built in Exception class provided by the C# runtime. The full list of built in Exception classes hasn’t been published yet by Microsoft at the time of this writing.

         EXCEPTION HANDLING

In the following program we use built in ArgumentException instead of OutOfRange exception.

A better way to handle an Argument exception

 

using system;

class Demo

{

int n;

public int []array;

public Demo (int n)

{

this.array = new int En];

this.n= n;

},

pub1ic void· show_element (int i)

{

try

{

i f (I == 0)

throw new ArgumentException (“Out of rannge”);

}

catch (ArgumentException e)

{

console.writeLine(“Exception :{0}”,e);

return ;

}

Console.WriteLine (array[i]);

.}

}

class Test

{

public static void Main()

{

Demo test = new Demo(3);

test.array[l] = 2;

test.array[2] =3;

test.show_element (0);

}

}

Following the last ‘catch’ box you can also include a ‘finally’ box. This code is guaranteed to run whether or not an exception is generated. It is especially useful for cleanup code where this would be skipped in the ‘try’ box following an exception being thrown.

Where an exception is not caught by any of the subsequent ‘catch’ boxes, the exception is thrown upwards to the code which called the method in which the exception occurred (note that in C# the methods do not declare what exceptions they are throwing). This exception will keep on bubbling upwards until it is either caught by some exception handling in the code or until it can go no further and causes the program to halt.

Note that the exceptions a program throws need not be limited to those automatically generated. A program can throw exceptions-including customized exceptions-whenever it wishes, using· the ‘throw’ command. The code below gives examples of all the statements discussed above, with the ‘getException’ method showing how. to throw an exception.

 

using System;

public class ExceptionDemo

{

public static void Main ()

{

try

{

getException();

}

catch (Exception e)

{

Console.writeLine(“we got an exception”);

}

finally

{

Console.writeLine(“The end of the program”);

}

}

public static void getException()

{

throw new Exception();

}

}

You’ll also like:

  1. Exception Handling in c++
  2. PHP Exception Handling
  3. Exception Handling in Python
  4. Exception Handling in Java with Examples
  5. Advantages of the Exception-Handling Mechanism
Next →
← Prev
Like/Subscribe us for latest updates     

About Dinesh Thakur
Dinesh ThakurDinesh Thakur holds an B.C.A, MCDBA, MCSD certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps.

Dinesh Thakur is a Freelance Writer who helps different clients from all over the globe. Dinesh has written over 500+ blogs, 30+ eBooks, and 10000+ Posts for all types of clients.


For any type of query or something that you think is missing, please feel free to Contact us.


Primary Sidebar

C# Tutorials

C# Tutorials

  • C# - .NET Languages Types
  • C# - Dot Net
  • C# - Dot Net Framework
  • C# - Inheritance Types
  • C# - Features
  • C# - CTS
  • C# - CLS
  • C# - CLR
  • C# - Console
  • C# - MSIL
  • C# - Base Class Library
  • C# - Web Forms Creation
  • C# - C# Vs C++
  • C# - Statements Types
  • C# - JIT
  • C# - CLI
  • C# - Controls Types
  • C# - String Types
  • C# - Execution Model

Other Links

  • C# - PDF Version

Footer

Basic Course

  • Computer Fundamental
  • Computer Networking
  • Operating System
  • Database System
  • Computer Graphics
  • Management System
  • Software Engineering
  • Digital Electronics
  • Electronic Commerce
  • Compiler Design
  • Troubleshooting

Programming

  • Java Programming
  • Structured Query (SQL)
  • C Programming
  • C++ Programming
  • Visual Basic
  • Data Structures
  • Struts 2
  • Java Servlet
  • C# Programming
  • Basic Terms
  • Interviews

World Wide Web

  • Internet
  • Java Script
  • HTML Language
  • Cascading Style Sheet
  • Java Server Pages
  • Wordpress
  • PHP
  • Python Tutorial
  • AngularJS
  • Troubleshooting

 About Us |  Contact Us |  FAQ

Dinesh Thakur is a Technology Columinist and founder of Computer Notes.

Copyright © 2025. All Rights Reserved.

APPLY FOR ONLINE JOB IN BIGGEST CRYPTO COMPANIES
APPLY NOW