0% found this document useful (0 votes)
5 views21 pages

Unit V

The document provides an overview of exception handling in C++, explaining its necessity over traditional error handling methods such as returning error numbers and abnormal termination. It details the components of exception handling, including try, throw, and catch blocks, and discusses predefined exceptions available in C++. Additionally, it includes examples of handling exceptions in C++ programs, emphasizing the importance of maintaining normal program flow despite runtime errors.

Uploaded by

driti s gowda
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views21 pages

Unit V

The document provides an overview of exception handling in C++, explaining its necessity over traditional error handling methods such as returning error numbers and abnormal termination. It details the components of exception handling, including try, throw, and catch blocks, and discusses predefined exceptions available in C++. Additionally, it includes examples of handling exceptions in C++ programs, emphasizing the importance of maintaining normal program flow despite runtime errors.

Uploaded by

driti s gowda
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 21

Unit V

Exception Handling: Introduction to Exception, Benefits of


Exception handling, Try and catch block Throw statement,
Pre-defined exceptions in C++.
Exception Handling
• Exceptions are runtime anomalies or abnormal
conditions that a program encounters during its
execution.
• Exception Handling in C++ is a process to handle
runtime errors. We perform exception handling so the
normal flow of the application can be maintained even
after runtime errors.
TRADITIONAL ERROR HANDLING
Traditionally, error handling is done in three different
ways, namely,

• returning error number


• global flag manipulation
• abnormal termination.
Returning Error Number:

• In this approach, when a function encounters an issue or


incorrect input, it returns an error code.
• For example, returning zero might indicate a successful
function call, while a non-zero value signals an error.
• However, there is no universal standard for error codes, and
different functions may use different codes for various errors.
• It requires users to check the returned error code after each
function call, and if they forget, unexpected results may
occur.
• Global flag manipulation, specifically referring to the use of
global variables to signal and handle errors, is a traditional
mechanism in error handling, particularly in the C
programming language. The most commonly used global
variable for this purpose is errno.
• errno is a global variable indicating the error occurred during
any function call and it is defined inside <errno.h> header file
• When a function is called in C, a variable named errno is
automatically assigned a code (value) which can be used to
identify the type of error that has been encountered. Different
codes (values) for errno mean different types of errors.
• The disadvantage of this method is the reliance on the user to
comply and test the value of the global flag every time the
function is called. If the user does not check the value of errno
and continues to work, there is a danger of getting unexpected
results.
errno value Error

1 Operation not permitted

2 No such file or directory

3 No such process

4 Interrupted system call

5 I/O error

6 No such device or address

7 The argument list is too long

8 Exec format error

9 Bad file number

10 No child processes

11 Try again

12 Out of memory

13 Permission denied
Abnormal Termination of Program:

• This involves terminating the program abruptly when an


error occurs, using functions like exit(), abort(), or
assert().
• assert() displays a message before terminating, but it
can still crash the program.
• Abnormal termination can leave files and resources
unclosed and the system in an inconsistent state.
• Recovering from such situations is difficult or
impossible, making this approach less recommended.
NEED FOR EXCEPTION
HANDLING
• Exception handling in C++ is introduced to address the
inadequacies of traditional error-handling mechanisms,
especially in scenarios involving objects and distributed
environments. The following reasons illustrate the need
for exception handling in these contexts:
• Dividing Error Handling
• Unconditional Termination
• Separating Error Reporting and Error Handling
• Problem of Destroying Objects
COMPONENTS OF EXCEPTION
HANDLING MECHANISM
The exception handling mechanism has
three building blocks, namely,
• try for indicating the program area
where the exception can be thrown,
• throw for throwing an exception,
• and catch for taking an action for the
specific exception
• The try statement allows you to define a block of code to be tested for
errors while it is being executed.
• The throw keyword throws an exception when a problem is detected,
which lets us create a custom error. This is a mechanism to generate
the exception. It is usually a single statement starting with the keyword
throw or a function call that contains throw inside its body. After the
execution of this statement, the control is transferred to the
corresponding catch block written immediately after the try block, if
the exception is thrown.
• The catch statement allows you to define a block of code to be
executed if an error occurs in the try block.
Example
• We use the try block to test some code: If the value of a variable “age”
is less than 18, we will throw an exception, and handle it in our catch
block.
Divide by zero program
#include <iostream>
using namespace std;

int main() { // not executed if denominator is 0


divide = numerator / denominator;
double numerator, denominator, divide; cout << numerator << " / " << denominator <<
" = " << divide << endl;
cout << "Enter numerator: ";
}
cin >> numerator;
catch (int num_exception) {
cout << "Enter denominator: ";
cout << "Error: Cannot divide by " <<
cin >> denominator; num_exception << endl;
try { }
return 0;
// throw an exception if denominator is 0 }
if (denominator == 0)
throw 0;
#include <iostream> int answer;
using namespace std; /*
Using a try catch block because in divison, the
int division(int a, int b) denominator can be 0.
{ So, we must handle the 0 divion inside try
block.
// checking if the denominator is 0 or not.
*/
if (b == 0)
try
{
{
// if the denominator is 0, then we must
throw an exception answer = division(x, y);
throw "Division by zero!"; cout << " Output: " << answer << endl;
} }
// if there is no exception, then we are // printing the thrown exception from the
returning the answer. function
return int(a / b); catch (const char *errorMessage)
} {
cout << errorMessage << endl;
int main() }
{
int x = 50; return 0;
}
Write a C++ program that demonstrates the use of exception handling to handle out-
of-range access to an array.
#include <iostream>
#include <stdexcept> // If the index is within the valid range, access the
using namespace std; array element
int main() { int value = myArray[index];
try { cout << "Value at index " << index << ": " << value <<
endl;
const int arrSize = 5; } catch (const out_of_range& e) {
int myArray[arrSize] = {1, 2, 3, 4, 5}; cerr << "Error: " << e.what() << endl;
int index; }
cout << "Enter an index to access the array: ";
cin >> index; return 0;
if (index < 0 || index >= arrSize) { }
throw out_of_range("Index out of range.");
}
a) Write a program that creates a Calculator class. The class contains two
variables of integer type. Design a constructor that accepts two values as
parameter and set those values.
• Design four methods named Add (), Subtract (), multiply (), Division ( ) for
performing addition, subtraction, multiplication and division of two numbers.
• For addition and subtraction, two numbers should be positive. If any
negative number is entered then throw an exception in respective methods. So
design an exception handler (ArithmeticException) in Add () and Subtract ()
methods respectively to check whether any number is negative or not.
• For division and multiplication two numbers should not be zero. If zero is
entered for any number then throw an exception in respective methods. So
design an exception handler (ArithmeticException) in multiply () and Division ()
methods respectively to check whether any number is zero or not.
Predefined Exceptions in C++
• C++ provides several standard exceptions as part of the <exception>
header, which serve as the base classes for handling common error
scenarios. These exceptions belong to the Standard Template Library
(STL) and are part of the Standard Exception Hierarchy.
1.Standard Exception Classes
std::exception:Base class for all standard
exceptions.Provides the what() virtual function to
return an error message.
2. Logic Errors
Logic errors are exceptions that occur due to issues in the program's logic.
•std::logic_error:
•Base class for logic-related exceptions.
•Includes:
•std::invalid_argument: Thrown when an invalid argument is provided to a function.
•std::length_error: Thrown when an operation exceeds the allowed length.
•std::out_of_range: Thrown when an operation attempts to access an element out of
range.
Runtime Errors
Runtime errors are exceptions that occur during program execution.
•std::runtime_error:
•Base class for runtime-related exceptions.
•Includes:
•std::overflow_error: Thrown when an arithmetic overflow occurs.
•std::underflow_error: Thrown when an arithmetic underflow occurs.
•std::range_error: Thrown when a result of a computation is out of
range.
Memory Exceptions
• std::bad_alloc:Thrown when the new operator fails to allocate
memory.
• STL-Related Exception
• sstd::bad_function_call:Thrown when calling an empty std::function.
Input/Output Exceptions
std::ios_base::failure:Thrown when an input/output operation fails.

You might also like