KwickAcademy Cyber Safety and Ethics · 9 min · free
Templates and Exception Handling in C++
A template writes one function or class for any type; exception handling uses try, throw and catch to recover from run time errors.
Follows the syllabus of: CBSE Class 9 Information Technology (402), CBSE Class 10 Information Technology (402)
On screen in this lesson
Why templates?
| Same logic is often needed for int, double and char |
| Copying a function for each type wastes time |
| A template is a pattern that works for any type |
| The compiler fills in the real type for you |
How a function template works
| typename T and class T mean the same thing here |
| The compiler reads the arguments to find T |
| big(3, 7) makes an int version of big |
| Both arguments must give the same T |
| big<double>(3, 7.5) names T yourself |
Class templates
| A class template is a class with a type placeholder |
| One design makes Box<int>, Box<char> and more |
| You must write the type in angle brackets |
| vector<int> from the STL is a class template |
Function vs class template
| Point | Function | Class |
|---|---|---|
| Starts with | template <..> | template <..> |
| Type written? | Usually not | Yes, Box<int> |
| Makes | a function | a class |
| Example | big(3, 7) | vector<int> |
What is an exception?
| An exception is an error that happens while running |
| Examples: divide by zero, wrong index, bad input |
| Without handling, the program may crash |
| Exception handling lets us catch it and recover |
Rules of catch
| catch type must match the thrown type |
| One try can have many catch blocks |
| They are checked from top to bottom |
| catch (...) catches anything; keep it last |
| No matching catch: program ends by terminate |
Quick answers
throw 404; with catch (const char*) then catch (int): which runs?
catch (int), printing code 404.
Where does catch (...) go?
Last.
KwickClips from this lesson
Short clips, one idea each. Good for revision the night before.
Who works out T?42 sec
Must you write the type for a class template?42 sec
Must the catch type match?41 sec
What does invalid_argument mean?40 secThe full lesson, in text
Hello students, welcome to Kwickprep. Can one function add whole numbers today and decimal marks tomorrow, without writing it twice? Yes, with a template! And what happens when a program divides by zero? Today we learn function templates, class templates, try, catch and throw, and the standard exceptions of C plus plus.
First, why do we need templates? Very often the same logic is needed for int, double and char values. Copying the same function three times wastes time, and a bug must then be fixed three times. A template is a pattern, like a stencil, that works for any data type. When you use it, the compiler fills in the real type for you.
Here is a function template. The line template, angle bracket, typename T, starts it. T is a placeholder for a type, like a blank in a form. The function big returns the bigger of a and b. The question mark and colon form the conditional operator. If a is greater than b, it gives a, otherwise b. With three and seven, T becomes int, so it prints seven. With two point five and one point five, T becomes double, so it prints two point five.
Let us see what really happens. Inside the angle brackets, typename T and class T mean exactly the same thing. The compiler looks at the arguments to work out what T is. So big of three and seven makes an int version of big, behind the scenes. Both arguments must give the same T. Pause and predict. What happens with big of three and seven point five? It is a compile error, because T cannot be int and double together. To fix it, name T yourself: big, angle bracket double, of three and seven point five.
Now, class templates. A class template is a class written with a type placeholder, just like a function template. One design can make a box of int, a box of char, or a box of any type. With a class, you write the type yourself inside angle brackets. You already use one if you know vector of int, because vector is a class template.
Here Box is a class template. It has one public member called val of type T, and a function get that returns it. Box of int, named a, holds five. Box of char, named b, holds the letter K. The same class design works for both. So the output is five followed by K.
Let us compare the two kinds. Both start with the word template and a placeholder in angle brackets. For a function template, the compiler usually works out the type from the arguments. For a class template, you write it, as in Box of int. A function template makes functions, and a class template makes classes. Big of three and seven is a function template call, and vector of int is a class template in use.
Now the second big idea, exceptions. An exception is an error that happens while the program is running, not while compiling. Examples are dividing by zero, using a wrong array index, or reading bad input. If nobody handles it, the program may crash, like an app that suddenly closes. Exception handling lets the program catch the problem and recover politely.
C plus plus uses three keywords. The try block holds code that might go wrong. The throw keyword sends out an exception when a problem is found. The catch block receives it and handles it. Here the variable named n is zero, so we throw the message Zero, as text. The line that divides is skipped completely. The catch block for text receives the message and prints Zero.
Let us draw how control moves. The program starts. It runs the statements inside the try block one by one. At each step, is an exception thrown? If yes, control jumps straight to the matching catch block, skipping the rest of try. If no, the try block finishes and every catch block is skipped. Either way, the program then continues after the catch blocks. Then it stops normally.
Learn five rules about catch. The type in catch must match the type that was thrown. One try block can have many catch blocks, one for each type. They are checked from top to bottom, and only the first match runs. Catch with three dots catches any exception, so always keep it last. If no catch matches, the program ends by calling a function named terminate.
Pause and predict. We throw four hundred four, like a page not found code. Which catch block runs? The first catch wants text, so it does not match. The second catch wants an int, so it matches. The output is code four hundred four.
C plus plus also gives ready made exception classes, called standard exceptions. Exception is the base class of all of them, so catching exception by reference catches every one. Out of range is thrown when an index is too big, such as a vector's at function with index ninety nine. Invalid argument is thrown when a conversion fails, such as stoi of abc, because abc is not a number. Runtime error is a general error you can throw yourself. Bad alloc is thrown when new cannot get memory. Most of these live in the header stdexcept.
Here we write std, double colon, in front of each name instead of using namespace std. The vector named v has only two values, at index zero and one. The at function checks the index before reading. Index five does not exist, so at throws out of range. The catch block receives it by reference, with the ampersand, and prints Bad index. Square brackets would not check, and could silently read garbage.
Imagine a mobile recharge app, where the wallet does not have enough money. We throw a runtime error with the message Low balance. The catch block asks for exception, the base class, so it also catches runtime error. The what function returns the message we gave. So the output is Low balance.
Let us revise what we learned today. A function template writes one function that works for any type T. A class template makes classes, and you write the type in angle brackets, as in Box of int. The try block holds risky code, and throw sends out an exception. Catch must match the thrown type, and catch with three dots always goes last. Standard exceptions such as out of range and runtime error are ready for you to use. Try writing a template function that returns the smaller of two values.
Courses that teach this
| Course | Unit |
|---|---|
| CBSE Class 9 Information Technology (402) | Digital Presentation |
| CBSE Class 10 Information Technology (402) | Digital Documentation (Advanced) using LibreOffice Writer |
| Programming All levels C++ | Templates, Exceptions and File Handling |
Voice-over in this lesson is AI-generated. The script is written and checked by Kajal Ma'am. Boards can revise a syllabus mid-year, so confirm anything you plan around against the official board circular. Keep your passwords, OTPs and ID numbers to yourself — we never ask for them. To reach Kajal Ma'am, use the WhatsApp button; sharing your number there is how we call you back.
Free to watch, no sign-up. Live classes with Kajal Ma'am are the paid course; these lessons stay free either way.

