0% found this document useful (0 votes)
2 views42 pages

Exception Handling 1

The document discusses exception handling in C++, explaining what exceptions are, their types (synchronous and asynchronous), and the mechanism for handling them using try, throw, and catch keywords. It provides examples of handling specific exceptions like division by zero and array index out of bounds, as well as techniques for multiple catch statements, rethrowing exceptions, and catching class types. Key points highlight the importance of proper exception handling to prevent program termination and ensure robust code.

Uploaded by

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

Exception Handling 1

The document discusses exception handling in C++, explaining what exceptions are, their types (synchronous and asynchronous), and the mechanism for handling them using try, throw, and catch keywords. It provides examples of handling specific exceptions like division by zero and array index out of bounds, as well as techniques for multiple catch statements, rethrowing exceptions, and catching class types. Key points highlight the importance of proper exception handling to prevent program termination and ensure robust code.

Uploaded by

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

Exception Handling

1
Exception
• Exceptions are the run time anomalies or unusual conditions
that a program may encounter while executing.

• Examples- division by zero, access to an array outside of its


bounds, running out of memory space.

• When a program encounters an exceptional condition, it is


important that it is identified and dealt with effectively.

2
Types of exceptions
• Synchronous – These are the types of exceptions for which
error handling could be written(Under the control of
program),Errors such as “out of range” and “over-flow” are
synchronous types of exceptions
• Asynchronous – Errors that are caused by events beyond the
control of the program (keyboard interrupts, Disk failure,
Hardware malfunctioning) are called asynchronous
exceptions.

Exception handling in C++ is designed to handle only


synchronous exceptions.

3
Exception handling
C++ provides exception handling mechanism for dealing with the
exceptions raised during the program execution. It follows following
steps to deal with exception

1. Find the problem (Hit the exception)


2.Inform that an error has occurred.(Throw an exception)
3.Receive the error information. (catch the exception)
4.Take corrective actions. (Handle the exception)

4
Exception handling mechanism
• C++ exception handling mechanism is basically built upon
three keywords, namely,
• Try: The keyword try is used to preface a block of statements
which may generate exceptions. This block of statements is
known as try block.
• Throw: when an exception is detected, it is thrown using a
throw statement in the try block.
• Catch: . it ‘catches’ the exception ‘thrown’ by the throw
statement in the try block, and handles it appropriately.
NOTE:
The catch block that catches an exception must immediately
follow the try block that throws the exception.
5
The block throwing exception

6
Exception handling mechanism
……
continued…
……
try
{
……
throw exception; //block of statements which
……. //detects and throws an exception
}
catch(type arg) //catches the exception
{
……
…… //block of statement that handles
} // the exceptions
………

7
Example 1: Division by Zero
#include<iostream> try
using namespace std; {
int main() if(n2==0)
{ throw n2; //Statement 1
int n1,n2,result; else
cout<<"\nEnter 1st number : "; {
cin>>n1; result = n1 / n2;
cout<<"\nEnter 2nd number : "; cout<<"\nThe result is : "<<result;
cin>>n2; }
}
catch(int x)
{
cout<<"\nCan't divide by : "<<x;
}
cout<<"\nEnd of program.";
}
8
Output
First run:
Enter 1st number : 10 10
Enter 2nd number :
The result is : 1
End of program.

Second run: //Here exception is raised and caught


Enter 1st number : 6
Enter 2nd number : 0
Can't divide by : 0
End of program.
9
Example 2-Array index out of bounds
#include<iostream> Output:
using namespace std;
int main() When the value of i becomes 5, we
{ are going out of the bounds of array,
int a[5]={1,2,3,4,5}; hence exception will be raised and
try caught through suitable catch block
{ and message which will be displayed
int i=0; is: array out of bounds 5
while(1)
{
cout<<a[i]<<endl;
i++;
if(i==5)
throw i;
}
}
catch(int j)
{
cout<<"array out of bounds"<<j;
}}
10
WAP
• You are tasked to write a program for age verification. The program will
prompt the user to enter their age. If the entered age is 18 or older, the
program will display a message saying "YES, you are old enough".
However, if the user enters an age below 18, the program will throw an
exception, and you need to handle the exceptional case gracefully.
• Input Format The input consists of the age of a user.
• Output Format If the entered age is 18 or older, the program will display
a message saying "YES, you are old enough".
• If the age is not valid, the output displays the error message.

11
12
#include <iostream>
Solution
using namespace std;
int main()
{
try
{
int age;
cin >> age;
if (age >= 18)
cout << "YES, you are old enough.";
else
throw (age);
}
catch (int num)
{
cout << "No, You must be at least 18 years old" << endl;
cout << "Current Age is : " << num;
} 13
return 0;}
Using throw outside of try block
or Invoking function that generates
the exception

14
Introduction
• A user defined function can also throw the exception, if its
body contains such lines of code, which may behave
abnormally on giving certain set of inputs.
• So, in that case throw keyword can be used inside the body of
user defined function, and it will be written for the condition
which may cause the exception.
• This is the case, where throw keyword is used outside of try
block, i.e. in function definition.
• User defined function will be called inside try block(usually in
main()), and if it throws the exception, then suitable catch
block will handle the exception.
• Syntax---In next slide
15
Syntax
type function(arg_list) //function with exception
{
…..
throw(object); //Throws exception
…….
}
…..
…..
try
{
…… //invoke function here, inside try
……
}
catch(type arg) //catches the exception
{
……….
………. //Handles exception here
} 16
Example
#include <iostream> int main()
using namespace std; {
void divide(int x, int y, int z) try
{ {
cout<<"We are inside the function"<<endl; cout<<"We are inside the try block"<<endl;
if((x-y)!=0) divide(10,20,30);
{ divide(10,10,20);
int R= z/(x-y); }
cout<<"Result="<<R<<endl; catch(int i)
} {
else cout<<"caught the exception"<<endl;
{ }
throw(x-y); return 0;
} }
}
17
Multiple catch statements
• A single try statement can have multiple catch statements.
• Execution of particular catch block depends on the type of
exception thrown by the throw keyword.
• Multiple catch blocks are used when we have to catch a
specific type of exception out of many possible type of
exceptions i.e. an exception of
type char or int or float or double etc.
• The catch block that matches with type of exception thrown is
executed, while the rest of catch blocks are skipped
• Depending upon the thrown type, suitable catch block will
work and error handling code will be executed
• Syntax is specified in next slide-

18
Multiple catch statements
try
{
// try block
}
catch(type1 arg)
{
//catch block1
}
catch(type2 arg)
{
//catch block2
}
………..
………..
catch(typeN arg)
{
//catch blockN
} 19
Example
#include<iostream> catch(char ch)
using namespace std; {
int main() cout<<"\nCharacter exception caught.";
{
}
int a=2;
try
catch(double d)
{ {
if(a==1) cout<<"\nDouble exception caught.";
throw a; //throwing integer exception }
else if(a==2) cout<<"\nEnd of program.";
throw 'A'; //throwing character exception }
else if(a==3)
throw 4.5; //throwing float exception
}
catch(int a)
{
cout<<"\nInteger exception caught.";
}

20
WAP
• Suppose you are developing a program that takes input from
users to determine the sentiment of their feedback. The
program requires users to enter a numeric value representing
their sentiment. The program uses exceptional handling to
categorize the sentiment into three categories: positive(1),
negative(-1), or neutral(0).

Write a program to find whether the given number is Positive,


Negative, or zero using the exceptional handling technique.
Pass different parameters for different catch methods.

21
Solution
#include <iostream>
using namespace std;
int main() {
try { catch(float f)
int feedback; {
cin >> feedback; cout << "You Entered Zero";
if (feedback > 0) }
throw "c"; return 0;
else if(feedback < 0) }
throw feedback;
else
throw 1.1f;
}
catch (const char *ch){
cout << "You Entered Positive number";
}
catch (int num) {
cout << "You Entered Negative Number";
} 22
WAP
• You are assigned to create a program that calculates the sum
of positive numbers in an array provided by the user. The
program should also handle exceptional situations when a
negative number is encountered in the array.

23
#include <iostream>
Solution
using namespace std;
int main() {
int n, sum = 0;
cin >> n;
int arr[n];
for(int i = 0; i < n; i ++){
cin >> arr[i];
}
try{
for(int i = 0; i < n; i ++){
if(arr[i] < 0){
throw i;
}
sum =sum+ arr[i];}}
catch(int ex){
cout << "Negative number found at index " << ex << endl;
} 24
cout << "The sum is : "<< sum;}
WAP
• You have been asked to create a program that calculates the
sum of digits for a three-digit number provided by the user.
The program should handle exceptional situations when the
input number is not a valid three-digit number. Print the sum if
it is a three-digit number, else print the error message.

25
Solution
#include <iostream>
using namespace std;
int sumOfDigit(int num){
int sum = 0;
while(num != 0){
sum =sum+ (num % 10);
num=num / 10;
}
return sum;}
int main() {
int num;
cin >> num;
try{
if(num >= 1000 || num < 100)
throw "It's not a three digit Number or valid number";
else
cout << "Sum of the digits is " << sumOfDigit(num); }
catch(const char* ex){
cout << ex; }}

26
Catch all exceptions
• In some situations, we may not be able to predict all possible
types of exceptions and therefore may not be able to design
independent catch handlers to catch them.
• In such situations, we can force a catch statement to catch all
exceptions instead of a certain type alone(Also known as generic
catch handler)
• catch all( or Generic catch handler) should always be the last
catch handler(or placed at the end) out of all available catch
handler
catch(…)
{
// Statements for processing
// all exceptions
} 27
Program Example-Catch all Exceptions
#include<iostream>
using namespace std;
int main()
{
int a=1;
try
{
if(a==1)
throw a; //throwing integer exception
else if(a==2)
throw 'A'; //throwing character exception
else if(a==3)
throw 4.5; //throwing float exception
}
catch(...)
{
cout<<"\nException occur.";
} 28
cout<<"\nEnd of program.";}
Catching class types as an Exception
• In the previous topics we have seen how values of basic types
can be thrown and caught
• We can also throw class types(or user defined types) from try
block and we can design a suitable catch block for the same
with an argument of class type
• Program example in the next slide

29
Catching Classvoid
types asamnt)
withdraw(int Exception
{
#include<iostream>
if(amnt>bal)
using namespace std; {
class insuffbal throw insuffbal();
{ }
else
public: {
void what_error() bal=bal-amnt;
{ cout<<"\nUpdated bal:"<<bal;
}
cout<<"Insufficient balance!"; }
} };
};
int main()
class account
{
{ account ob(5000);
int bal; try
{
public:
ob.withdraw(200000);
account(int b) }
{ catch(insuffbal& e)
bal=b; {
30
e.what_error();
Rethrowing an exception
• If a catch block cannot handle the particular exception it has
caught, then we can rethrow the exception to the next catch
block, so that it can be handled properly
• Rethrowing causes 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.
• In such situations, we may invoke throw without any
arguments as: throw;
• Program example in the next slide

31
#include <iostream>
Example
using namespace std;
int main()
{
try
{
try
{
throw 200;
}
catch(int y)
{
cout<<"Inner\n";
throw;
}
}
catch(int a)
{
cout<<"Outer\n";
} 32
}
Example
#include<iostream> int main()
using namespace std; {
void divide(double x, double y) cout<<"Inside main"<<endl;
{ try
cout<<"Inside function"<<endl; {
try divide(10.5,2.0);
{ divide(20.0, 0.0);
if(y==0.0) }
throw y; //Throwing double catch(double)
else {
cout<<"Division="<< x/y<<endl; cout<<"caught double inside
} main"<<endl;
catch( double) // Catch a double }
{ cout<<"end of main"<<endl;
cout<<"caught double inside function"<<endl; return 0;
throw; // Rethrowing double }
}
cout<<"end of function"<<endl;
}
33
OUTPUT
• Inside main
• Inside function
• Division=5.25
• end of function
• Inside function
• caught double inside function
• caught double inside main
• end of main

• When an exception is rethrown, it will not be caught by same catch


statement or any other catch in that group.
• It will be caught by an appropriate catch in the outer try/catch
sequence only

34
Key points with respect to Exception handling
1. Implicit type conversion doesn’t happen for primitive types. For
example, in the following program ‘a’ is not implicitly converted to int
#include <iostream>
using namespace std;
int main()
{
try {
throw 'a';
}
catch (int x) {
cout << "Caught " << x;
}
catch (...) {
cout << "Default Exception\n";
}
return 0;
}
35
Key points with respect to Exception handling
2. If an exception is thrown and not caught anywhere, the program terminates
abnormally. For example, in the following program, a char is thrown, but there
is no catch block to catch a char.
#include <iostream>
using namespace std;
int main()
{
try {
throw 'a';
}
catch (int x) {
cout << "Caught ";
}
return 0;
}
36
Key points with respect to Exception handling
3. In C++, try-catch block can be nested
#include <iostream>
using namespace std;
int main()
{
try {
try {
throw 20;
}
catch (int n) {
cout << "Handle Partially ";
throw; //Re-throwing an exception
}
}
catch (int n) {
cout << "Handle remaining ";
}
return 0;
} 37
Key points with respect to Exception handling

4. If there are statements after throw, and exception has been


thrown, then those statements will not execute, as control will be
shifted to catch block
5. When an exception is thrown, all objects created inside the
enclosing try block are destructed before the control is transferred
to catch block.

Program example for point 5 in next slide

38
Example
#include <iostream> int main() {
using namespace std; try {
class Test { Test t1;
public: throw 10;
Test() } catch(int i) {
{ cout << "Caught " << i << endl;
cout << "Constructor of Test " << }
endl; } }
~Test() Output:
{ cout << "Destructor of Test " << Constructor of Test
endl; } Destructor of Test
}; Caught 10

39
Practice Questions-Homework
1) Write a program to take input for an integer, if that integer
value is prime, then throw an exception with a message :
"Prime input caused an exception", and if the input is non-
prime, then nothing should happen.

2) Write a program to create a user defined function: check(),


which takes input for 2 integers, if the square of the sum of
these two integers is odd, then this function should throw an
exception, with message: "Invalid inputs caused an exception".
Call this function in main() function, and also prepare a
suitable catch block to handle the exception thrown by this
function.

40
Practice Questions-Homework
3) Create a user defined function: Test(), which accepts marks of 5
subjects as an arguments(i.e. 5 integer arguments), it calculates the
total of these marks, if the total of the marks is a multiple of 3, then
throw integer value: 0, if total of the marks is a multiple of 5, then
throw float value: 0.0, else if the total of the marks is a multiple of 7,
then throw a character constant: 'Z'. Now call this function in the
main(), and pass the arguments into this function, prepare suitable
catch blocks(Multiple) to handle the exceptions thrown by this
function.

4) Create a user defined function: Test1(), which takes integer


argument, if the passed argument is a multiple of 3, then rethrow the
exception, catch the same integer value in another catch block and in
this check whether the caught integer value is multiple of 5 or not. If
it is then display: "Problem", otherwise display: "Ok“.
41
Practice Questions-Homework
5) Write a program to create a class: Checking with integer data
member: int x, there is a member function: void getdata(), there
is a function check(), if the input is even, then throw the class
object, and call the display() member function with message:
"Invalid“

42

You might also like