You are on page 1of 12

Exception Handling

❖ What is Exception
An exception is a problem that arises during the execution of a program. A C# exception
is a response to an exceptional circumstance that arises while a program is running, such
as an attempt to divide by zero.

Exceptions provide a way to transfer control from one part of a program to another. C#
exception handling is built upon four keywords: try, catch, finally, and throw.

❖ Rules for Handling Exception

try
{
// code that may raise exceptions
}
catch(Exception ex)
{
// handle exception
}
finally
{
// final cleanup code
}
• try − A try block identifies a block of code for which particular exceptions is activated. It
is followed by one or more catch blocks.
• catch − A program catches an exception with an exception handler at the place in a
program where you want to handle the problem. The catch keyword indicates the
catching of an exception.
• finally − The finally block is used to execute a given set of statements, whether an
exception is thrown or not thrown. For example, if you open a file, it must be closed
whether an exception is raised or not.
• throw − A program throws an exception when a problem shows up. This is done using
a throw keyword.
Exception classes and its important properties

Exception type Description

Exception Base class for all exceptions.

IndexOutOfRangeException Thrown by the runtime only when an array is indexed


improperly.

NullReferenceException Thrown by the runtime only when a null object is


referenced.
Exception type Description

InvalidOperationException Thrown by methods when in an invalid state.

ArgumentException Base class for all argument exceptions.

ArgumentNullException Thrown by methods that do not allow an argument to be


null.

ArgumentOutOfRangeException Thrown by methods that verify that arguments are in a


given range.

Understanding & using try, catch keywords

C# provides a structured solution to the exception handling in the form of try and catch
blocks. Using these blocks the core program statements are separated from the error-
handling statements.

These error handling blocks are implemented using the try, catch, and finally keywords.
Following is an example of throwing an exception when dividing by zero condition occurs

using System;
namespace ErrorHandlingApplication {

class DivNumbers {
int result;

DivNumbers() {
result = 0;
}

public void division(int num1, int num2) {


try {
result = num1 / num2;
} catch (DivideByZeroException e) {
Console.WriteLine("Exception caught: {0}", e);
} finally {
Console.WriteLine("Result: {0}", result);
}
}

static void Main(string[] args) {


DivNumbers d = new DivNumbers();
d.division(25, 0);
Console.ReadKey();
}
}
}
❖ Throwing exceptions

Throw keyword generates (or translates) exceptions. By using a throw statement inside a
catch block, we can change the resulting exception.

Example 1:

using System;

public class ThrowTest


{
public static void fn(Int32 age)
{
if (age < 0)
{
// throw an argument out of range exception if the age is
// less than zero.
throw new ArgumentOutOfRangeException("Age Cannot Be Negative ");
}
}

public static void Main()


{
try
{
fn(-10);
}

catch (Exception e)
{
Console.WriteLine(String.Concat(e.StackTrace, e.Message));
Console.ReadLine();
}
}
}

Importance of finally block

Code in finally blocks is always executed. Finally provides a construct for ensuring the
correct execution of programs. It ensures a block of statements are always reached before
the enclosing method is exited.

class program{
static void Main(string[] args){

object str = "Questpond";


try{
int i = (int)str;
}catch (Exception ex){

Console.WriteLine("Error Occurred {0}",ex.Message.ToString());


}
finally{
Console.WriteLine("Finally : Cleaning Resources");
}
}
}

❖ Writing Custom Exception Classes

We have seen built-in exception classes in the previous section. However, you often like to
raise an exception when the business rule of your application gets violated. So, for this you
can create a custom exception class by deriving Exception or ApplicationException class.

The .Net framework includes ApplicationException class since .Net v1.0. It was designed to
use as a base class for the custom exception class. However, Microsoft now
recommends Exception class to create a custom exception class.

using System;
public class InvalidAgeException : Exception
{
public InvalidAgeException(String message)
: base(message)
{

}
}
public class TestUserDefinedException
{
static void validate(int age)
{
if (age < 18)
{
throw new InvalidAgeException("Sorry, Age must be greater than 18");
}
}
public static void Main(string[] args)
{
try
{
validate(12);
}
catch (InvalidAgeException e) { Console.WriteLine(e); }
Console.WriteLine("Rest of the code");
}
}

Output:

InvalidAgeException: Sorry, Age must be greater than 18


Rest of the code
❖ Using I/O Class
Streams Class

A stream is an ordered sequence of bytes, which is send from one application or input
device to another application or output device. These bytes are written and read one after
the other and always arrive in the same order as they were sent. Streams are
an abstraction of a data communication channel that connects two devices or applications.

System.IO.Stream is an abstract class that provides standard methods to transfer bytes


(read, write, etc.) to the source. It is like a wrapper class to transfer bytes. Classes that
need to read/write bytes from a particular source must implement the Stream class.

Text Stream and Binary Stream

Binary Streams

Binary streams, as their name suggests, work with binary (raw) data. You probably guess
that that makes them universal and they can be used to read information from all sorts of
files (images, music and multimedia files, text files etc.). We will take a brief look over
them, because we will currently focus on working with text files.

The main classes that we use to read and write from and to binary streams are: File
Stream, Binary Reader and Binary Writer.

The class File Stream provides us with various methods for reading and writing from a
binary file (read / write one byte and a sequence of bytes), skipping a number of bytes,
checking the number of bytes available and, of course, a method for closing the stream.
We can get an object of that class by calling him his constructor with parameter-a file
name.

The class Binary Writer enables you to write primitive types and binary values in a specific
encoding to a stream. It has one main method – Write(…), which allows recording of any
primitive data types – integers, characters, Booleans, arrays, strings and more.

Binary Reader allows you to read primitive data types and binary values recorded using
a Binary Writer. Its main methods allow us to read a character, an array of characters,
integers, floating point, etc. Like the previous two classes, we can get on object of that
class by calling its constructor.

Text Streams

Text streams are very similar to binary, but only work with text data or rather a sequence
of characters (char) and strings (string). Text streams are ideal for working with text files.
On the other hand, this makes them unusable when working with any binaries.

The main classes for working with text streams in .NET are Text Reader and Text Writer.
They are abstract classes, and they cannot be instantiated. These classes define the basic
functionality for reading and writing for the classes that inherit them. Their more important
methods are:

- ReadLine() – reads one line of text and returns a string.


- ReadToEnd() – reads the entire stream to its end and returns a string.
- Write() – writes a string to the stream.
- WriteLine() – writes one line of text into the stream.

❖ System.IO and Base classes of Stream

The System.IO namespace has various classes for performing various operation with files,
like creating and deleting files, reading from or writing to a file, closing a file and so on.

Some important classes are as follows:

I/O Class Description


FileStream Used to read from and write to any location in a file
BinaryReader Reads primitive data from a binary stream
BinaryWriter Writes primitive data in binary format
File Use for manipulating files
StreamReader Used for reading characters from a byte stream
StreamWriter Is used for writing characters to a stream
StringReader Is used for reading from a string buffer
StringWriter Is used for writing into a string buffer
Directory Helps in manipulating a directory structure
DirectoryInfo Used for performing operations on directories

Now we see examples of some important I/O class and examine the outputs.

The FileStream Class

The FileStream class in the System.IO namespace helps in reading from, writing to and
closing files. This class derives from the abstract class Stream. You need to create a
FileStream object to create a new file or open an existing file. The syntax for creating a
FileStream object is as follows:

1. FileStream <object_name> = new FileStream( <file_name>,<FileMode Enum


erator>, <FileAccess Enumerator>, <FileShare Enumerator>);

For example, create a FileStream object F for reading a file named Example.txt as:

1. FileStream My_File = new FileStream("Example.xlsx", FileMode.Open, FileAcce


ss.ReadWrite, FileShare.ReadWrite);

Now we see the meaning of each parameter.

FileMode
The FileMode enumerator defines various methods for opening files. The members of the
FileMode enumerator are:

Mode Description
It opens an existing file and puts cursor at the end of file, or creates the
Append
file, if the file does not exist
Create It creates a new file. If file is already exist then it will overrite that file
It will also use to create a new file If the file is already exist then it will
CreateNew
throw an Exception
Open It opens an existing file
It specifies to the operating system that it should open a file if it exists,
OpenOrCreate
otherwise it should create a new file
Truncate It opens an existing file and truncates its size to zero bytes

FileAccess

The FileAccess enumerator defines the kind of task to do with the file.

AccessMode Description
Read Data can be read from file
Write Data can be written to the file
ReadWrite Data can be written to and read from the file

FileShare

This enumerator applies the type of permission for sharing.

SharingMode Description
Inheritable It allows a file handle to pass inheritance to the child processes
None It declines sharing of the current file
Read It allows opening the file for reading
ReadWrite It allows opening the file for reading and writing
Write It allows opening the file for writing

❖ Console I/O Streams

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();
Console. writeline ("Name: {0}", FirstName) ;

Working with File System -File , FileInfo, Directory , DirectoryInfo classes

The Directory class exposes static methods for creating, moving, and exploring
directories. All the methods of the Directory class are static, and therefore you can call
them all without having an instance of the class.

The DirectoryInfo class is a similar class but one which has nothing but instance
members (i.e., no static members at all). DirectoryInfo derives from FileSystemInfo, which
in turn derives from MarshalByRefObject. The FileSystemInfo class has a number of
properties and methods that provide information about a file or directory.

The DirectoryInfo object can also return a collection of all the files in each subdirectory
found. The GetFiles( ) method returns an array of FileInfo objects, each of which describes
a file in that directory. The FileInfo and File objects relate to one another, much as
DirectoryInfo and Directory do. Like the methods of Directory, all the File methods are
static; like DirectoryInfo, all the methods of FileInfo are instance methods.

File Class:- File class provided Static Method. It means that there is no need to create the
object of the class for access the class Methods.we already know that static member can
access through the class directly.

FileInfo Class:- FileInfo Class provided the Non Static Method.It means that we will need
to create the object of the class for access class methods. Class is loaded in memory
when the object of the class will be created.

using System;
using System.IO;

namespace FileHandlingArticleApp
{
class Program
{
static void Main(string[] args)
{
if(File.Exists("test.txt"))
{
string content = File.ReadAllText("test.txt");
Console.WriteLine("Current content of file:");
Console.WriteLine(content);
}
Console.WriteLine("Please enter new content for the file:");
string newContent = Console.ReadLine();
File.WriteAllText("test.txt", newContent);
}
}
}

Example of FileInfo Class:


Creating a File

using System;
using System.IO;
namespace CSharpProgram
{
class Program
{
static void Main(string[] args)
{
try
{
// Specifying file location
string loc = "F:\\abc.txt";
// Creating FileInfo instance
FileInfo file = new FileInfo(loc);
// Creating an empty file
file.Create();
Console.WriteLine("File is created Successfuly");
}catch(IOException e)
{
Console.WriteLine("Something went wrong: "+e);
}
}
}
}

Writing to a File
using System;
using System.IO;
namespace CSharpProgram
{
class Program
{
static void Main(string[] args)
{
try
{
// Specifying file location
string loc = "F:\\abc.txt";
// Creating FileInfo instance
FileInfo file = new FileInfo(loc);
// Creating an file instance to write
StreamWriter sw = file.CreateText();
// Writing to the file
sw.WriteLine("This text is written to the file by using StreamWriter class.");
sw.Close();
}catch(IOException e)
{
Console.WriteLine("Something went wrong: "+e);
}
}
}
}

Reading from a File


using System;
using System.IO;
namespace CSharpProgram
{
class Program
{
static void Main(string[] args)
{
try
{
// Specifying file to read
string loc = "F:\\abc.txt";
// Creating FileInfo instance
FileInfo file = new FileInfo(loc);
// Opening file to read
StreamReader sr = file.OpenText();
string data = "";
while ((data = sr.ReadLine()) != null)
{
Console.WriteLine(data);
}
}
catch (IOException e)
{
Console.WriteLine("Something went wrong: " + e);
}
}
}
}
Directory and DirectoryInfo Classes can be used to get some information or for doing
some manipulation regarding Directory.This classes are basically used for Directory
Manipulation.
▪ Directory Class Provide Static Method.
▪ DirectoryInfo class provide Non Static Method.

Example of Directory Class:- There are some steps to understand the Directory
Class in C# Which is given below:

using System;
using System.IO;
using System.Windows.Forms;
namespace Directory_class
{
class Program
{
static void Main(string[] args)
{
if (Directory.Exists(“dirname”))
{
String[] sfile = Directory.GetFiles(“sometext”);
foreach (String s in sfile)
{
Console.WriteLine(“”+s);
}
}
else
{
Directory.CreateDirectory(textBox1.Text);
Console.WriteLine("Directory created");
}
}
}
}

Example of DirectoryInfo Class:-

using System;
using System.IO;
using System.Windows.Forms;
namespace Directoryinfo_class
{
class Program
{
static void Main(string[] args)
{
DirectoryInfo dinfo = new DirectoryInfo(“dirname”);
if (dinfo.Exists)
{
FileInfo[] sinfo = dinfo.GetFiles();
foreach (FileInfo s in sinfo)
{
Console.WriteLine(“”+s);;
}
}
else
{
dinfo.Create();
Console.WriteLine(" New Directory has been created");
}
}
}
}

Example of TextReader and TextWriter class

using (TextWriter writer = File.CreateText("f:\\textFile.txt"))


{
writer.WriteLine("The first line with text writer");
}
using (TextReader txtR = File.OpenText("f:\\textFile.txt"))
{
String data = txtR.ReadToEnd();
Console.WriteLine(data);
}

You might also like