Operator overloading and exception handling - C# FOR BEGINNERS CRASH COURSE (2014)

C# FOR BEGINNERS CRASH COURSE (2014)

Chapter 13 Operator overloading and exception handling

13.1 Introduction to Operator Overloading

The built in operators can be redefined or overloaded in C#. The overloaded operators are functions having an operator keyword. It is followed by the symbol for the operator to be defined. The overloaded operator has a return type and a parameter list.

Example:

Example 50:

using System;

namespace operator1

{

class Room

{

private int length;

private int breadth;

public int getArea()

{

return length * breadth;

}

public void setlen (int len)

{

length = len;

}

public void setbread(int bread)

{

breadth = bread;

}

//+ operator is overloaded

public static Room operator + (Room r, Room s)

{

Room o = new Room();

o.length = r.length + s.length;

o.breadth = r.bread + s.bread;

return o;

}

}

class Program

{

public static void Main(string[] args)

{

Room o1 = new Room();

Room o2 = new Room();

Room o3 = new Room();

int area = 0;

//Room 1 specification

o1.setlen(10);

o1.setbread(5);

//Room 2 specification

o2.setlen(5);

o2.setbread(10);

//area of room 1

area = o1.getArea();

Console.WriteLine("Area of Room 1 is:{0}",area);

//area of room2

area = o2.getArea();

Console.WriteLine("Area of Room 2 is:{0}",area);

//Adding two objects

o3 = o1 + o2;

//Area of Room 3

area = o3.getArea();

Console.WriteLine("Area of Room 3 is:{0}",area);

Console.Read();

}

}

}

When the code is compiled and executed, the output is:

Area of Room 1 is: 50

Area of Room 2 is: 150

Area of Room 3 is: 225

13.2 Different operators in overloading

The operators that can be overloaded in C# are as mentioned below:

Operators

Description

+, -,*,/,%

Binary operators has two operands and can be overloaded

+,-,!,~,++,--

Unary operators take one operand and can be overloaded

&&, ||

Conditional logical operators. They cannot be overloaded directly

==, !=, <,>,<=,>=

Comparison operators. They cannot be overloaded

=, . , ?: , new, is, sizeof, typeof

They cannot be overloaded

+=, -=, *=, /=, %=

Assignment operators and cannot be overloaded

13.3 Introduction to exception handling

An exception is an error that occurs during the execution of a program. The exception occurs when an operation is not completed normally, thus the system throws an error when an exception occurs.

C #exception handling is based on four keywords: try, catch, finally and throw.

· try: Try block checks the block of code for a particular exception when activated. One or more catch blocks are present.

· catch: The catch keyword is used to catch the exceptions. A program catches an exception at a place in the program where user wants to handle the issue.

· finally: The finally block is used to execute statements even if the exception is thrown or not.

· throw: The throw keyword is used to throw an exception.

Syntax:

try

{

//statements causing exception

}

catch( ExceptionName e1 )

{

//error handling code

}

catch( ExceptionName e2 )

{

//error handling code

}

catch( ExceptionName eN )

{

//error handling code

}

finally

{

//statements to be executed

}

13.4 Exception classes in C#

There are several exception classes which are directly or indirectly derived from the System.Exception class. Some of the classes that are derived from the System.Exception class are System.ApplicationException and System.SystemException classes.

For a user-defined application having its own exception, the exception must be inherited from the ApplicationException class.

The System.SystemException class is the base class for all exceptions.

Exception class

Description

System.IO.IOException

It handles the I/O Errors

System.NullReferenceException

Errors generated during the process of dereferencing a null object

System.IndexOutOfRangeException

Errors generated when a method refers an array element out of bound

System.DivideByZeroException

Errors generated during the process of dividing the dividend by zero

System.OutOfMemoryException

Memory allocation to the application errors

System.InvalidCastException

Errors due to type casting

System.StackOverflowException

The errors generated due to stack overflow

13.5 Exception handling

The structured solution in the form of try and catch block is provided by C#. The core program statements are divided from the error handling statements. The finally block is used to handle errors.

Example:

Example 51:

using System;

namespace DivNumbers

{

class Divide

{

int output;

Divide()

{

output = 0;

}

public void division(int no1, int no2)

{

try

{

output = no1 / no2;

}

catch(DivideByZeroException e)

{

Console.WriteLine("Exception handled:{0}",e);

}

finally

{

Console.WriteLine("Output is:{0}",output);

}

}

public static void Main(string[] args)

{

Divide d = new Divide();

d.division(5,0);

Console.Read();

}

}

}

When the code is compiled and executed, the output is:

Exception handled: System.DivideByZeroException: Attempted to divide by zero

Output is: 0

13.6 User defined exceptions

Users can create their own exception classes when the situation arises where the user needs to handle an exception in a special way using custom code. These exceptions are known as user defined exceptions.

The user defined exceptions classes are derived from the ApplicationException class.

Example 52:

using System;

namespace userdefined

{

class Average

{

static void Main(string[] args)

{

Perform p = new Perform();

try

{

p.CalAverage();

}

catch(CountZeroException e)

{

Console.WriteLine("CountZeroException: {0}",e.Message);

}

Console.Read();

}

}

}

public class CountZeroException:ApplicationException

{

public CountZeroException(string message):base(message)

{

}

}

public class Perform

{

int no1 = 0;

int count = 0;

float average;

public void CalAverage()

{

if(count == 0)

{

throw(new CountZeroException("Count is zero in calculation"));

else

{

average = no1 / count;

}

}

}

}

When the code is compiled and executed, the output is:

CountZeroException: Count is zero in calculation