Exceptional Handling: try and catch, multilevel exceptional- throw and
throws - finally
Introduction
It is normal to commit mistakes in programming that prompts
unusual conditions called errors. These errors are classified as:
Syntax Errors - Errors that occur when you violate the rules of
writing C++ syntax, e.g, missing paranthesis
Logical Errors - These errors solely depend on the
logical thinking of the programmers.
Runtime Errors - Errors which occur during program
execution(run-time) after successful compilation are called
run-time errors, e.g, division by zero
Semantic errors - Errors due to an improper use of
program statements
The errors that occur at run-time are known as
exceptions.
They occur due to different conditions such as division by zero,
accessing
an element out of bounds of an array, unable to open a file, running out of
memory and so on
Exception Handling in C++ is defined as a method that takes care of a
surprising condition like runtime errors.
At whatever point a sudden situation happens, there is a
movement of the program control to a unique function
known as Handlers.
Exceptions
Indicate problems that occur during a program’s execution Occur
frequently
Exceptions provide a way to transfer control from one part of a program
to another.
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.
Exception handling
• Can resolve exceptions
• Allow a program to continue executing or
• Notify the user of the problem and
• Terminate the program in a controlled manner
• Makes programs robust and fault-tolerant
Types of Exception
Two types of exception:
Synchronous Exceptions
Asynchronous Exceptions
Synchronous Exceptions
• Occur during the program execution due to some fault in the input data or
technique that is not suitable to handle the current class of data, within the
program .
• For example:
• errors such as out of range
• Overflow
• underflow and so on
Asynchronous Exceptions
• Caused by events or faults unrelated (external) to the program and beyond
the control of the program.
For example
errors such as keyboard interrupts
hardware malfunctions
disk failure and so on
The exception handling mechanism of C++ is designed to handle
only synchronous exceptions within a program.
Exception levels
Exceptions can occur at many levels:
1.Hardware/operating system level.
• Arithmetic exceptions; divide by 0.
• Memory access violations; stack over/underflow.
2.Language level.
• Type conversion; illegal values, improper casts.
• Bounds violations; illegal array indices.
• Bad references; null pointers.
3. Program level.
• User defined exceptions.
Need of Exceptions
• Detect and report an “exceptional circumstance”
• Separation of error handling code from normal code
• Functions / Methods can handle any exception they choose
• Grouping of Error types
Mechanism
1. Find the problem (Hit the exception)
2. Inform that an error has occurred (Throw the exception)
3. Receive the error information (Catch the exception)
4. Take corrective actions (Handle the exception)
C++ Standard Exceptions
C++ Standard Exceptions
Exception Description
std::exception An exception and parent class of all the standard C++
exceptions.
std::bad_alloc This can be thrown by new.
std::bad_cast This can be thrown by dynamic_cast.
std::bad_exception This is useful device to handle unexpected exceptions in a
C++ program
std::bad_typeid This can be thrown by typeid.
Exception Description
std::logic_error An exception that theoretically can be detected by
reading the code.
std::domain_error This is an exception thrown when a mathematically
invalid domain is used
std::invalid_argument This is thrown due to invalid arguments.
std::length_error This is thrown when a too big std::string is created
std::out_of_range This can be thrown by the at method from for example a
std::vector and std::bitset<>::operator[]().
Exception Description
std::runtime_error An exception that theoretically can not
be detected by reading the code.
std::overflow_error This is thrown if a mathematical
overflow occurs.
std::range_error This is occured when you try to store a
value which is out of range.
std::underflow_error This is thrown if a mathematical
underflow occurs.
Exceptions: keywords
Handling the Exception is nothing but converting system error message into
user friendly error message Exception handling use three keywords for
handling the exception
try
catch
throw
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 an exception 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.
Simple Exceptions : syntax
try
{
throw exception;
……… }
catch(type arg)
{
………. ………..
} ……. …….
Exceptions
Simple Exceptions : Example
#include<iostream>
using namespace std;
int main()
{
int a,b,c;
cout << "Enter a & b" << endl;
cin >> a>> b;
try
{
if (b!=0)
{
c=a/b;
cout << “Result=" << c << endl;
}
else
{
throw(b);
}
}
catch(int i)
{
cout <<“Exception Caught”<<endl;
}
}
OUTPUT:
Enter A & B : 4 0
Exception Caught
Enter a & b: 6 3
Result= 2
#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)
Nested try blocks
try
{
……..
try
{
………
}
catch (type arg)
{
………
}
}
catch(type arg)
{
……….
………..
}
Multiple Catch Exception
• Used when a user wants to handle different exceptions differently.
• For this, a user must include catch statements with different declaration.
• It is possible to design a separate catch block for each kind of exception
• Single catch statement that catches all kind of exceptions
• Syntax
catch(…)
{
…….
}
Note :
A better way to use this as a default statement along with other catch statement so
that it can catch all those exception which are not handle by other catch statement
Multiple catch statement : Syntax
try
{
……..
}
catch (type1 arg)
{
………
}
catch (type2 arg)
{
………
}
……..
catch(typeN arg)
{
………..
}
Multiple Exceptions : Example
#include <iostream>
using namespace std;
int main()
{
int choice;
try
{
cout<<"Enter any choice: ";
cin>>choice;
if(choice == 0)
cout<<"Multiple Catch"<<endl;
else if(choice == 1)
throw (100); //throw integer value
else if(choice == 2)
throw ('x'); //throw character value
else if(choice == 3)
throw (1.23f); //throw float value
else
cout<<"Not Valid Choice"<<endl;
}
catch(int a)
{
cout<<"Integer Exception Block, value is: "<<a<<endl;
}
catch(char b)
{
cout<<"Character Exception Block, value is: "<<b<<endl;
}
catch(float c)
{
cout<<"Float Exception Block, value is: "<<c<<endl;
}
return 0;
}
OUTPUT:
Enter any choice: 0
Multiple Catch
Enter any choice: 1
Integer Exception Block, value is: 100
Enter any choice: 2
Character Exception Block, value is: x
Enter any choice: 3
Float Exception Block, value is: 1.23
Enter any choice: 4
Not Valid Choice
Topic: throw, throws and finally
Throwing Exception
When an exception is detected, it is thrown using throw statement in the
try block
It is also possible, where we have nested try-catch statement
throw;
It cause the current exception to be thrown to the next enclosing
try/catch sequence and is caught by a catch statement listed after that
enclosing try block.
Rethrowing Exception
Handle Any Type of Exceptions (...)
If you do not know the throw type used in the try block, you can use the "three
dots" syntax (...) inside the catch block, which will handle any type of exception.
The throw point
• Used to indicate that an exception has occurred
• It is called “throwing an exception”
• Throw normally specifies an operand:
• Will be caught by closest exception handler
The throw point: Example
try
{
if(denominator == 0)
{
throw denominator;
}
result = numerator/denominator;
cout<<"\nThe result of division is:" <<result;
}
Finally
The application always executes any statements in the finally part, even if an
exception occurs in the try block. When any code in the try block raises an
exception, execution halts at that point.
Once an exception handler is found, execution jumps to the finally
part. After the finally part executes, the exception handler is called.
If no exception occurs, the code in the finally block executes in the
normal order, after all the statements in the try block.
Finally
Finally - Syntax
try
{
// statements that may raise an
exception
}
__finally
{
// statements that are called even
//if there is an exception in the try block
}
Exceptional Handling: User-defined exceptions
User Defined Exceptions
• We can define your own exceptions by inheriting and overriding exception class
functionality.
• User defined exception classes inherit exception class provided by C++
and overrides it’s functionality according to our needs.
• To use class exception, we must include exception header using the pre-
processor directive.
#include <exception>
Rules for User Defined Exceptions
• Always include exception header using pre-processor directive at the very first
step.
• The function which will return an exception string should have a return
type of char followed by *,
char* what()
{
// codes here
}
char is as return type because we will return a
string
• Should have a try and catch block.
User Defined Exceptions- Example
User Defined Exceptions
Example
• Let’s say that the password must consists of at least 6 characters.
• If we write a exception for this case, when the program receives a password in
length of 5 characters it will throw an exception so that we could
know the password is not valid