• 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# » C# libraries

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();

}

}

FILE I/O in C#

By Dinesh Thakur

Files are the great way to store data between instances of your application, or file can be used to transfer data between applications. All input and output in the .NET framework involve the abstract base class Stream. The Stream class supports reading and writing bytes. Stream integrates asynchronous support. Its default implementations define synchronous reads and writes in terms of their corresponding asynchronous methods, and vice versa.

All classes that represent streams inherit from the’ Stream class. The Stream class and its derived classes provide a generic view of data sources and repositories, isolating the programmer from the specific details of the operating system and underlying devices.

Streams involve these fundamental operations:

• Streams can be read from.

Reading is the transfer of data from a stream into a data structure, such as an array of bytes.

• Streams can be written to.

Writing is the transfer of data from a data source into a stream.

• Streams can support seeking.

Seeking is the querying and modifying of the current position within a stream.

Depending on the underlying data source or repository, streams might support only some of these capabilities. For example, NetworkStreams do not support seeking there are type of streams:

 

• Output streams: These are used to write data on the external sources such as phesical disk file, a network location, a printer or another program.

• Input streams: These are used to read data into memory or variables that your program can access. Mostly used input stream is keyboard. An input stream can come from almost any source.

Classes for Input and Output

The System.IO namespace contains almost all of the classes for reading and writing data to and from files, you must reference this in your application to gain access to theses classes. Stream supports· synchronous and asynchronous reads and writes. The .NET Framework provides a number of classes derived from Stream, including FileStream, MemoryStream, and NetworkStream. In addition, there is a BufferedStream class, which provides buffered I/O and which can be used in conjunction with any of the other stream classes. The principal classes involved with I/O are summarized in Table.

       The principal classes

Reading Text File

 

The following code examples show how to read text from a text file. The second example notifies you when the end of the file is detected.

using System;

using System.IO;

 

class Test

{

public static void Main()

{

try

{

// Create an instance of StreamReader to read from a file.

// The using statement also closes the StreamReader.

using (streamReader sr = new streamReader(“TestFile.txt”))

{

string line;

// Read and disp1ay 1ines from the fi1e until the end of

// the file is reached.

while ((line = sr.Readline()) != null)

{

console.writeline(line);

}

}

}

catch (Exception e)

{

// let the user know what went wrong.

Conso1e.writeline( “The fi1e cou1d not be read:”);

Console.writeline(e.Message);

}

}

}

 

using System;

using system.IO;

public class TextFromFile

{

private const string FILE_NAME= “MyFile.txt”;

public static void Main(String[] args)

{

if (!File.Exists(FILE_NAME)).

{

console.writeLine(“{0} does not exist.”, FILE_NAME);

return;

}

using (streamReader sr = File.openText(FILE_NAME))

{

String input;

while ((input=sr.ReadLine())!=null)

{

console.writeLine(input);

}

Console.writeline (“The end of the stream has been reached.”);

sr.close();

}

}

 

Writing Text File

 

The first example shows how to add text to an e2cisting file. The second example shows how to create a new text file and write a string to it. Similar functionality can be provided by the WriteAlIText methods.

 

using system;

using system.Io;

class Test

{

public static void Main()

{

// Create an instance of streamwriter to write text to a

file.

// The using statement also closes the Streamwriter.

using (Streamwriter sw = new streamwriter(UTestFile.txt”))

{

// Add some text to the file.

sw.write(“This is the U);

sw.Writeline(‘header for the file.”);

sw.writeLine(“——-“);

II Arbitrary objects can also be written to the file.

sw.write(“The date is: ”);

sw.writeLine(DateTime.Now);

}

}

}

 

using system;

using system.Io;

public class TextToFile

{

private const string FILE_NAME = “MyFi1e.txt” ;

public static void Main(String[] args)

{

if (File.ExistS(FILE_NAME))·

{

Console.writeLine(“{O} already exists.”, FILE_NAME);

return;

}

using (streamwriter sw = File.createText(FILE_NAME))

{

sw.WriteLine (“This is my file.”);

sw.WriteLine (“I can write ints {OJ or floats {1}, and so

on. ” ,1, 4.2);

sw.close();

}

}

}

Reading and Writing to a Newly Created Data/Binary File

 

The BinaryWriter and BinaryReader classes are used for writing and reading data, rather than character strings. The following code example demonstrates writing data to and reading data from a new, empty file stream (Test. data). After creating the data file in the current directory, the associated BinaryWriter and BinaryReader are created, and the Binary Writer is used to write the integers 0 through 10 to Test.data, which leaves the file pointer at the end of the file. After setting the file pointer back to the origin, the BinaryReader reads out the specified content.

 

using system;

using System.IO;

class MyStream

{

private const string FILE_NAME = “Test.data”;

public static void Main(String[] args)

{

// Create the new, empty data f’l1e.

if (Fi1e.ExistS(FILE_NAME))

{

console.writeLine(“{O} already exists!”, FILE_NAME);

return;

}

Fi1eStream fs = new Filestream (FILE_NAME, FileMode.createNew);

// Create the writer for data.

Binarywriter w = new Binarywriter(fs);

// write data to Test.data.

for (int i = 0; i < 11; i++)

{

w.write( (int) i);

}

w.c1ose();

fs.c1ose();

// Create the reader for data.

fs = new FileStream(FILE_NAME, FileMode.open, Fi1eAccess.Read);

BinaryReader r = new BinaryReader(fs);

// Read data from Test.data.

for (int i = 0; i< 11; i++)

{

console.writeLine(r. ReadInt32 ());

}

r.C1ose();

fs.C1ose() ;

}

}

If Test.data already exists in the current directory, an IOException is thrown. Use FileMode.Create to always create a new file without throwing an IOException.

Console Input-Output in C#

By Dinesh Thakur

Console Input

The Console class allows using the Write () and the WriteLine () functions to display things on the screen. While the Console.Write () method is used to display something on the screen, the Console class provides the Read () method to get a value from the user. To use it, the name of a variable can be assigned to it. The syntax used is:

variableName = Console. Read();

This simply means that, when the user types something and presses Enter, what the user had typed would be given (the word is assigned) to the variable specified on the left side of the assignment operator.

Read() doesn’t always have to assign its value to a variable. For example, it can be used on its own line, which simply means that the user is expected to type something but the value typed by the user would not be used for any significant purpose. For example some versions of C# (even including Microsoft’s C# and Borland C#Builder) would display the DOS window briefly and disappear. You can use the Read() function to wait for the user to press any key in order to close the DOS window.

Besides Read(), the Console class also provides the ReadLine() method. Like the WriteLine() member function, after performing its assignment, the ReadLine() method sends the caret to the next line. Otherwise, it plays the same role as the Read() function.

 

string FirstName;

Console.write(“Enter First Name: “);

FirstName = console.ReadLine();

 

In C#, everything the user types is a string and the compiler would hardly analyze it without your explicit asking it to do so. Therefore, if you want to get a number from the user, first request a string. after getting the string, you must convert it to a number. To perform this conversion, each data type of the .NET Framework provides a mechanism called Parse. To use Parse(), type the data type, followed by a period, followed by Parse, and followed by parentheses. In the parentheses of Parse, type the string that you requested from the user.

 

Here is an example:

 

using system;

namespace GeorgetownCleaningservices

{

class orderprocessing

{

static void Main()

{

int Number;

string strNumber;

strNumber = console.ReadLine();

Number = int.parse(strNumber);

}

}

}

Console Output

Instead of using two Write() or a combination of Write() and WriteLine() to display data, you can convert a value to a string and display it directly. To do this, you can provide two strings to the Write() or WriteLine() and separate them with a comma:

1. The first part of the string provided to Write() or WriteLine() is the complete string that would display to the user. This first string itself can be made of different sections:

(a) One section is a string in any way you want it to display

(b) Another section is a number included between an opening curly bracket “{“and a closing curly bracket “}”.This combination of”{” and “}”is referred to as a, placeholder.

You can put the placeholder anywhere inside of the string. The first placeholder must have number O. The second must have number 1, etc. With this technique, you can create the string anyway you like and use the placeholders anywhere inside of the string

2. The second part of the string provided to Write() or WriteLine() is the value that you want to display. It can be one value if you used only one placeholder with 0 in the first string. It’ you used different placeholders, you can then provide a different value for each one of them in this second part, separating the values with a comma

Here are examples:

 

Demonstration of Writeline method

 

using System;

 

// An Exercise class

class Exercise

{

static void Main()

{

String FullName = “Anselme Bogos”;

int Age = 15;

double Hsalary = 22.74;

Console. writeline (“Full Name: {0}”, Full Name) ;

console.writeline(“Age: {0}”, Age);

console.writeline(“Distance: {0}”, Hsalary);

console.writeline(“Name: {0}\n Age: {1}\n Distance:{2}”,

FullName, Age, Hsalary);

Console.writeline();

}

}

 

OUTPUT:

 

Full Name: Anselme Bogos

Age: 15

Distance: 22.74

Full Name: Anselme Bogos

Age: 15

Distance: 22.74

 

As mentioned already, the numeric value typed in the curly brackets of the first part is an ordered number. If you want to display more than one value, provide each incremental value in its curly brackets. The syntax used is:

 

write(“To Display {0} {l} {2} {n}, First, second, Third, nth);

 

You can use the sections between a closing curly bracket and an opening curly bracket to create a meaningful sentence.

The System names pace provides a specific letter that you can use in the Write() or WriteLine()’s placeholder for each category of data to display. To format a value, in the placeholder of the variable or value, after the number, type a colon and one of the appropriate letter from the following table. If you are using ToStringO, then, in the parentheses of

ToString(), you can include a specific letter or combination inside of double-quotes. The letters and their meanings are:

                              Char used For

Use of particular character in writeline method

 

using System;

 

// An Exercise class

class Exercise

{

static void Main()

{

double Distance = 248.38782;

int Age = 15;

int Newcolor = 3478;

double Hsal = 22.74, Hrswork = 35.5018473;

double weeklysal = Hsal * Hrswork;

Console.writeLine(“Distance: {OJ”, Distance.ToString(“E”));

console.writeLine(“Age: {O}”, Age.ToStringO);

consol e.writeLine(“color: {O}”, Newcolor .Tostring(“x”));

Console.writeLine(“weekly salary: {OJ for .{1} hours”,

weeksal.ToString(“c”), Hrswork.ToString(“F”));

console.writeLine();

}

}

 

OUTPUT:

 

Distance: 2.483878E+002

Age: 15

color: D96

weekly salary: $807.31 for 35.50 hours

 

To specify the amount of space used to display a string, you can use its placeholder in Write() or WriteLine(). To do this, in the placeholder, type the 0 or the incrementing number of the placer and its formatting character if necessary and if any. Then, type a comma followed by the number of characters equivalent to the desired width. Here are examples:

 

Demonstration of Alinement in Writeline method

 

using System;

// An Exercise class

class Exercise

{

static void Main()

{

String Full Name = “Anselme 80gos”;

int Age = 15;

double Marks = 22.74;

 

console.writeline(“Full Name: {O,20}”, Full Name);

Console.writeline(“Age: {O,14}”, Age.ToString());

console.writeline(“Marks:{O:C,8}”, Marks.ToString());

Console. writeline(“——————————“) ;

Console.writeline();

}

}

 

OUTPUT:

 

Full Name:         Anselme bogos

Age: 15

Marks: $22.74

 

The sign you provide for the width is very important. If it is positive, the line of text is aligned to the right. This should be your preferred alignment for numeric values. If the number is negative, then the text is aligned to the left.

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