0% found this document useful (0 votes)
35 views

C++ Module 5

The document discusses different types of errors that can occur in programs. It explains compile time errors and run time errors. It then discusses exception handling in C++ using try, catch and throw keywords to handle errors and exceptions. It provides examples of handling different types of exceptions and advantages of exception handling.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views

C++ Module 5

The document discusses different types of errors that can occur in programs. It explains compile time errors and run time errors. It then discusses exception handling in C++ using try, catch and throw keywords to handle errors and exceptions. It provides examples of handling different types of exceptions and advantages of exception handling.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Errors can be broadly categorized into two types. We will discuss them one by one.

Compile Time Errors


Run Time Errors
Compile Time Errors – Errors caught during compiled time is called Compile time errors. Compile time
errors include library reference, syntax error or incorrect class import.

Run Time Errors - They are also known as exceptions. An exception caught during run time creates
serious issues.

Errors hinder normal execution of program. Exception handling is the process of handling errors and
exceptions in such a way that they do not hinder normal execution of the system. For example, User
divides a number by zero, this will compile successfully but an exception or run time error will occur due
to which our applications will be crashed. In order to avoid this exception handling techniques is used in
code.

In C++, Error handling is done using three keywords:


try
catch
throw

syntax
try
{
//code
throw parameter;
}
catch(exceptionname ex)
{
//code to handle exception
}

try block
The code which can throw any exception is kept inside(or enclosed in) atry block. Then, when the code
will lead to any error, that error/exception will get caught inside the catch block.

catch block
catch block is intended to catch the error and handle the exception condition. We can have multiple
catch blocks to handle different types of exception and perform different actions when the exceptions
occur. For example, we can display descriptive messages to explain why any particular exception
occurred.

throw statement
It is used to throw exceptions to exception handler i.e. it is used to communicate information about
error. A throw expression accepts one parameter and that parameter is passed to handler.
throw statement is used when we explicitly want an exception to occur, then we can use throw
statement to throw or generate that exception.

Understanding Need of Exception Handling


Let's take a simple example to understand the usage of try, catch and throw.
Below program compiles successfully but the program fails at runtime, leading to an exception.

#include <iostream>#include<conio.h>
using namespace std;
int main()
{
int a=10,b=0,c;
c=a/b;
return 0;
}
The above program will not run, and will show runtime error on screen, because we are trying to divide
a number with 0, which is not possible.

How to handle this situation?


We can handle such situations using exception handling and can inform the user that you cannot divide
a number by zero, by displaying a message.
Using try, catch and throw Statement
Now we will update the above program and include exception handling in it.
#include <iostream>
#include<conio.h>
using namespace std;
int main()
{
int a=10, b=0, c;
// try block activates exception handling
try
{
if(b == 0)
{
// throw custom exception
throw "Division by zero not possible";
c = a/b;
}
}
catch(char* ex) // catches exception
{
cout<<ex;
}
return 0;
}

In the code above, we are checking the divisor, if it is zero, we are throwing an exception message, then
the catch block catches that exception and prints the message.

Doing so, the user will never know that our program failed at runtime, he/she will only see the message
"Division by zero not possible".
Using Multiple catch blocks
Below program contains multiple catch blocks to handle different types of exception in different way.
#include <iostream>
#include<conio.h>
using namespace std;

int main()
{
int x[3] = {-1,2};
for(int i=0; i<2; i++)
{
int ex = x[i];
try
{
if (ex > 0)
// throwing numeric value as exception
throw ex;
else
// throwing a character as exception
throw 'ex';
}
catch (int ex) // to catch numeric exceptions
{
cout << "Integer exception\n";
}
catch (char ex) // to catch character/string exceptions
{
cout << "Character exception\n";
}
}
}

In the above program, if the value of integer in the array x is less than 0, we are throwing a numeric
value as exception and if the value is greater than 0, then we are throwing a character value as
exception. And we have two different catch blocks to catch those exceptions.

Standard Exceptions in C++


There are some standard exceptions in C++ under <exception> which we can use in our programs. They
are arranged in a parent-child class hierarchy which is depicted below:

std::exception - Parent class of all the standard C++ exceptions.


logic_error - Exception happens in the internal logical of a program.
domain_error - Exception due to use of invalid domain.
invalid argument - Exception due to invalid argument.
out_of_range - Exception due to out of range i.e. size requirement exceeds allocation.
length_error - Exception due to length error.
runtime_error - Exception happens during runtime.
range_error - Exception due to range errors in internal computations.
overflow_error - Exception due to arithmetic overflow errors.
underflow_error - Exception due to arithmetic underflow errors
bad_alloc - Exception happens when memory allocation with new() fails.
bad_cast - Exception happens when dynamic cast fails.
bad_exception - Exception is specially designed to be listed in the dynamic-exception-specifier.
bad_typeid - Exception thrown by typeid

Advantage of exception handling


1. Separating Error-Handling Code from "Regular" Code:- Exceptions provide the means to
separate the details of what to do when something out of the ordinary happens from the main
logic of a program. In traditional programming, error detection, reporting, and handling often
lead to confusing spaghetti code. Exceptions enable you to write the main flow of your code and
to deal with the exceptional cases elsewhere.
2. Propagating Errors Up the Call Stack:- A second advantage of exceptions is the ability to
propagate error reporting up the call stack of methods.
3. Grouping and Differentiating Error Types:- Because all exceptions thrown within a program are
objects, the grouping or categorizing of exceptions is a natural outcome of the class hierarchy.
4. Remove error-handling code from the software’s main line of code.
5. A method writer can chose to handle certain exceptions and delegate others to the caller.
6. An exception that occurs in a function can be handled anywhere in the function call stack.
7. Separating Error-Handling Code from “Regular” Code.
8. Propagating Errors Up the Call Stack.

Important questions

1. Which keyword is used to handle the exception?


A. Try
B. Throw

C. Catch
D. None of the above
Explanation: Catch keyword is used to handle the exception

2. Which is used to throw a exception?


A. Try
B. Throw
C. Catch
D. None of the above
Ans : B
Explanation: Throw is used to throw a exception.

3. We can prevent a function from throwing any exceptions.


A. TRUE
B. FALSE
C. May Be
D. Can't Say
Ans : A
Explanation: True, We can prevent a function from throwing any exceptions.

4. Return type of uncaught_exception() is ___________.


A. int
B. bool
C. char *
D. double
Ans : B
Explanation: Return type of uncaught_exception() is bool.

5. Which of the following statements are true about Catch handler?


i) It must be placed immediately after try block T.
ii) It can have multiple parameters.
iii) There must be only one catch handler for every try block.
iv) There can be multiple catch handler for a try block T.
v) Generic catch handler can be placed anywhere after try block.

A. Only i, iv, v
B. Only i, ii, iii
C. Only i, iv
D. Only i, ii
Ans : C
Explanation: Only i, iv statements are true about Catch handler.

6. Which type of program is recommended to include in try block?


A. Static memory allocation
B. Dynamic memory allocation
C. Const reference
D. Pointer
Ans : B
Explanation: While during dynamic memory allocation, Your system may not have sufficient resources to
handle it, So it is better to use it inside the try block.

7. What is the output of this program?


#include <iostream>
using namespace std;

int main()
{
try
{
throw 'b';
}
catch (int param)
{
cout << "Int Exception";
}
catch (...)
{
cout << "Default Exception";
}
cout << "After Exception";
return 0;
}
A. Default Exception After Exception
B. Int Exception After Exception
C. Int Exception
D. Default Exception
Ans : A
Explanation: The block catch(...) is used for catch all, when a data type of a thrown exception doesn't
match with any other catch block, the code inside catch(...) is executed. Note that the implicit type
conversion doesn't happen when exceptions are caught. The character 'a' is not automatically converted
to int.

8. What is the output of this program?


#include <iostream>
using namespace std;

int main()
{
int P = -1;
try {
cout << "Inside try";
if (P < 0)
{
throw P;
cout << "After throw";
}
}
catch (int P ) {
cout << "Exception Caught";
}
cout << "After catch";
return 0;

}
A. Inside try Exception Caught After throw After catch
B. Inside try Exception Caught After catch
C. Inside try Exception Caught
D. Inside try After throw After catch
Ans : B
Explanation: When an exception is thrown, lines of try block after the throw statement are not
executed. When exception is caught, the code after catch block is executed. Catch blocks are generally
written at the end through.

9. What will be the output of the following program?

#include <iostream>
using namespace std;
int main( )
{
try
{
string strg1("Test");
string strg2("ing");
strg1.append(strg2, 4, 2);
cout << strg1 << endl;
}
catch (exception &LFC)
{
cout << "Caught: " << LFC.what() << endl;
cout << "Type: " << typeid(LFC).name() << endl;
};
return 0;
}
A. out of range
B. bad type_id
C. bad allocation
D. none of the mentioned
Ans : A
Explanation: As we are using out of bound value on strings, So it arising an exception.
10. Which illustrate predefined exceptions
A. Memory allocation error
B. I/O error
C. Both A and B
D. None of the above
Ans : C
Explanation: Both A and B illustrate predefined exceptions.

You might also like