Friday, 17 February 2023

Unit 6: Template and Exception Handling (8)

 

Unit 6: Template and Exception Handling (8)

6.1. Concept of Template

6.2  Function overloading and problems

6.3 Function Template

6.4 Overloading function Template

6.5 Class Template

6.6 Derived class template

6.7 Concept of error handling

6.8 Basic of exception handling

6.9. Exception handling mechanism: throw, catch and try

Practical Works:

·       Create and apply function template

·       Create and apply template class

·       Apply try, catch and throw methods in program

 

6.1. Concept of Template

What is Templates in C++?

Templates in C++ is defined as a blueprint or formula for creating a generic class or a function. To simply put, you can create a single function or single class to work with different data types using templates. 

C++ template is also known as generic functions or classes which is a very powerful feature in C++. A keyword “template” in C++ is used for the template’s syntax and angled bracket in a parameter (t), which defines the data type variables.

Types of Templates in C++

There are two types of templates in C++

  • Function template
  • Class templates


What is the function template in C++?

Function template in C++ is a single function template that works with multiple data types simultaneously, but a standard function works only with one set of data types.

C++ Function Template Syntax

1

2

3

4

template<class type>ret-type func-name(parameter list)

{

//body of the function

}

Here, type is a placeholder name for a data type used by the function. It is used within the function definition.

The class keyword is used to specify a generic type in a template declaration.

C++ function template example:

Source Code:

#include<iostream.h>

using namespace std;

template<classX>

X func(Xa,Xb)

{

return a;

}

int main()

cout<<func(15,8),,endl;

cout,,func('p','q'),,endl;

cout<<func(7.5,9.2),,endl;

return();

}

Output:

15
p
7.5

6.3 Function overloading and problems

Function overloading is a C++ programming feature that allows us to have more than one function having same name but different parameter list, when we say parameter list, it means the data type and sequence of the parameters, for example the parameter list of a function myfunc(int a,int b) is (int, float) which is different from the function myfunc(float a, int b) parameter list (float, int).

Example of function overloading in c++:

#include<iostream>

using namespace std;

class Addition

{

Public:

    int sum(int num1, int num2);

  {

     return num1+num2;

  }

 

    int sum(int num1, int num2, num3);

  {

 

    return num1+num2+num3;

 

   }

 

 

};

int main(void)

{

  Addition obj;

  cout<<obj.sum(20,15)<<endl;

  cout<<obj.sum(81,100,10);

  return();

}

Output:

31
191

 

What is class template in c++?

The class template in c++ is like function templates. They are known as generic templates. They define a family of classes in C++. 

Syntax of Class Template

1

2

3

4

5

template<class Ttype>

class class_name

{

//class body;

}

Here Ttype is a placeholder type name, which will be specified when a class instantiated.

The Ttype can be used inside the body of the class.   

Class template in c++ example:

Source Code:

#include<iostream.h>

using namespace std;

template <class C>

class A{

private;

C,a,b;

public:

A(Cx,Cy){

a=x;

b=y;

}

void show()

}

count<<"The Addition of"<<a<<"and"<<b<<"is"<<add()<<endl;

}

C add(){

C c=a+b;

return c;

}

};

int main(){

Aaddint(8,6);

Aaddfloat(3.5,2.6);

Aaaddouble(2.156,5.234);

Aaddint.show();

cout<<endl;

adddouble.show();

count<<endl;

return 0;

}

 

Output:

The addition of 8 and 6 is 14
Addition of 3.5 and 2.6 is 6.1
The addition of 2.156 and 5.234 is 7.390

Overloading function of template

C++ function overloading, the function can have different data types as well as different number of parameters, but in case of templates, the overloading happens only with number of parameters, as it can already handle many data types. The overloading of function templates can be explained with following example.

#include<iostream.h>

#include<conio.h>

template <class T>

T Max (T a, T b)

  {

   if (a>b)

      return a;

   else

      return b;

 

  }

T Max (T a, T b, T c)

  {

   if (a>b && a>c)

      return a;

   else if(b>a && b>c)

      return b;

   else

      return c;

 

  }

 

void main()

{

int a,b,c;

clrscr();

cout<<”enter three number:”;

cin>>a>>b>>c;

cout<<”Maximum number among”<<a<<” and “<<b<<” is: <<max(a,b)<<endl;

cout<<”Maximum number among”<<a<<”,”<<b<<” and “<<c<<” is: <<max(a,b,c);

getch();

}

 

Output:

Enter three number:1 4 65
Maximum number among 1 and 4 is :4
Maximum number among 1, 4 and 65 is:65

 

6.7 Concept of error handling

Error may occur due to human mistakes or system failure while writing a program. Any program may contain error may be four types.

1.     Compiler/Syntax Error:

The syntax error occurs either due to typing mistake in syntax or by writing wrong syntax. These types of errors occur from incorrectly written code, such as an incorrectly type keyword or incorrectly spelled variables. The reason of syntax error are:

a.      due to mistake in grammatical rules used in declaration of identifier.

b.     Use of undefined identifiers in program.

c.      Non-termination of statement by semicolon.

d.     Not providing equal number of opening and closing braces etc.

Program having syntax error:

#include<iostream.h>

int main()

 

int a

cout<<”a=”<<a;

return 0;

2.     Logical Error:

The program having logical error is compiled and executed successfully but does not produce desire result. The logical error may be due to:

a.      incorrect algorithm and procedure

b.     incorrect formula or expression

c.      incorrect use of identifiers.

Write a program to illustrate logical errors:

#include<iostream.h>

Void main()

   {

       float cent, fah;

       cout<<”enter temperature in centigrade:”;

       cin>>cent;

       fah=1.4*cent+32;

       cout<<”the equivalent Fahrenheit value is:”<<fah;

   }

Output:

Enter temperature in centigrade:-40

The equivalent Fahrenheit value is :-24

 

3.     Linker Error

During linking phase, the error will occur due to function prototyping and incorrect header files, this type of error is known as linking or linker error.

Write a program to illustrate linker errors:

#include<iostream.h>

#include<conio.h>

Void sum (int, int)

Void main()

   {

       clrscr();

       Sum (10, 20);

       getch();

      

   }

4.     Run Time Error

Run time error is such type of error which occurs during execution of the program. The program having run time error is compiled successfully but error occurs while execution of the program. Write a program to illustrate run time errors:

#include<iostream.h>

Void main()

   {

       float dividend, divider, quo;

       cout<<”enter value of dividend:”;

       cin>>divident;

       cout<<”enter value of divider:”;

       cin>>divider;

       quo=dividend/divider;

       cout<<”the result of division is :”<<quo;

            

   }

 

Output:

First run (with no error)

Enter value of dividend: 9

Enter value of divider: 2

The result of division is : 4.5

 

second run (with run time error)

Enter value of dividend: 9

Enter value of divider: 0

The result of division is : 0

Abnormal program termination

 

6.8 Basic of exception handling

An exception is an abnormal condition that arises in a program at run time. Thus exception is run time error. Lets consider the following program:

Program without exceptional handling:

#include<iostream.h>

Void main()

   {

       float a, result;

       cout<<”enter a number:”;

       cin>>a;

       result=100/a;

       cout<<”the result is:”<<result;

      

           

   }

The above program is correct in normal situation. It asks for a number and provides result dividing 100 by the number. But sometimes it can cause an error at run time if user gives zero as input value. When users enter 0 as input value, the program generates exception. It is called exception because the program generates such types of error in abnormal condition only (i.e. no error in normal condition).

 

Some abnormal conditions that may arise in program are:

1.       Dividing a number by zero [divide by zero]

2.       Short of memory

3.       Trying to open non-existing file for read only mode.

4.       Exceeding index of the array from its size.

5.       Attempting to initialize an object to an impossible value.

Exception handling model:

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 three keywords: try, catch, and throw.




  throw − A program throws anexception when a problem shows up. This is done using a throw keyword.

·       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.

·       try − A try block identifies a block of code for which particular exceptions will be activated. It's followed by one or more catch blocks.

Assuming a block will raise an exception, a method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception. Code within a try/catch block is referred to as protected code, and the syntax for using try/catch as follows −

try {
   // protected code
} catch( ExceptionName e1 ) {
   // catch block
} catch( ExceptionName e2 ) {
   // catch block
} catch( ExceptionName eN ) {
   // catch block
}

Following is a simple example to show exception handling in C++. The output of program explains flow of execution of try/catch blocks. 

#include <iostream>

using namespace std;

 

int main()

{

   int x = -1;

 

   // Some code

   cout << "Before try \n";

   try {

      cout << "Inside try \n";

      if (x < 0)

      {

         throw x;

         cout << "After throw (Never executed) \n";

      }

   }

   catch (int x ) {

      cout << "Exception Caught \n";

   }

 

   cout << "After catch (Will be executed) \n";

   return 0;

}

Output: 

Before try

Inside try

Exception Caught

After catch (Will be executed)

 

No comments:

Post a Comment

Teaching Method in ICT Education | Syllabus | Seven Semester | BICTE

  Course Title: Teaching Method in ICT Education Course No.: ICT. Ed. 478                                            Nature of ...