0% found this document useful (0 votes)
7 views49 pages

Exception handling

The document provides an overview of exception handling in C++, detailing types of errors, the mechanics of try, catch, and throw keywords, and how to manage exceptions effectively. It includes examples of exception handling, rethrowing exceptions, and the relationship between exception handling and inheritance. Additionally, it discusses standard exceptions in C++ and provides case studies to illustrate practical applications of exception handling.

Uploaded by

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

Exception handling

The document provides an overview of exception handling in C++, detailing types of errors, the mechanics of try, catch, and throw keywords, and how to manage exceptions effectively. It includes examples of exception handling, rethrowing exceptions, and the relationship between exception handling and inheritance. Additionally, it discusses standard exceptions in C++ and provides case studies to illustrate practical applications of exception handling.

Uploaded by

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

1

SDF II(15B11CI211)
EVEN Semester

2nd Semester , First Year


Jaypee Institute Of Information Technology (JIIT), Noida
2

Module 6: Introduction to Exceptions, Try, Catch and


Throw
3

Contents

• Types of Errors
• Introduction to Exceptions, Try, Catch and Throw
• Re-throwing exceptions, Exception and Inheritance
• Case Study of Exceptions
4

Types of Errors
• Errors can be broadly categorized into two types.
• 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.
5

Difference between Error and Exception handling

• 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 we can include exception handling in our code.
6

Exception Handling in C++

• The process of converting system error messages into user friendly error message
is known as Exception handling.
• This is one of the powerful feature of C++ to handle run time error and maintain
normal flow of C++ application.
• Exception : An exception is an event, which occurs during the execution of a
program, that disrupts the normal flow of the program's Instructions.
7

Exception Handling in C++: Examples of exception

• Exceptions are runtime anomalies that a program encounters during execution.


• It is a situation where a program has an unusual condition and the section of code
containing it can't handle the problem.
• Exception includes condition such as division by zero, accessing an array outside its
bound, running out of memory, etc.
• In order to handle these exceptions, exception handling mechanism is used which
identifies and deal with such condition.
8

Exception handling mechanism

• Exception handling mechanism consists of following parts:


• Find the problem (Hit the exception)
• Inform about its occurrence (Throw the exception)
• Receive error information (Catch the exception)
• Take proper action (Handle the exception)
9

Exception Handling in C++

• Handling the Exception : Handling the exception is converting system error


message into user friendly error message.
• Three keywords for Handling the Exception in C++ Language, they are;
• Try
• catch
• throw
10

Exception Handling in C++: try block

• try: Try block consists of the code that may generate exception. Exception are
thrown from inside the try block.
• try: represents a block of code that can throw an exception.
• "try" block groups one or more program statements with one or more catch
clauses.
11

Exception Handling in C++ : throw block

• throw: Throw keyword is used to throw an exception encountered inside try


block. After the exception is thrown, the control is transferred to catch block.

• Raising of an exception is done by "throw" expression.


12

Exception Handling in C++: catch block

• catch: Catch block catches the exception thrown by throw statement from try
block. Then, exception are handled inside catch block.

• catch :The catch block defines the action to be taken, when an exception occur.
13

Exception Handling in C++


14

Exception Handling in C++


15

Multiple Catch Exception

• Multiple catch exception statements are used when a user wants to handle
different exceptions differently.
• For this, a user must include catch statements with different declaration.
16
17

Catch all Exceptions

• Sometimes, it may not be possible to design a separate catch block for each kind
of exception. In such cases, we can use a single catch statement that catches all
kinds of exceptions.
18

Catch all Exceptions

• Sometimes, it may not be possible to design a separate catch block for each kind
of exception. In such cases, we can use a single catch statement that catches all
kinds of exceptions.
19

Example without Exception Handling


#include<iostream>
using namespace std;
int main()
{
int number, ans;
number=10;
ans=number/0;
cout<<"Result: "<<ans;
}
Note: Abnormally terminates program
20

Catch block

• The catch block contain the code to handle exception.


• The catch block is similar to function definition.

• Data-type specifies the type of exception that catch block will handle, Catch block will
receive value, send by throw keyword in try block.
Multiple Catch Blocks 21
#include <iostream>

using namespace std;

int main() {

int a=2;

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(int a) { cout<<"\nInteger exception caught."; }

catch(char ch) { cout<<"\nCharacter exception caught."; }

catch(double d) { cout<<"\nDouble exception caught."; }

cout<<"\nEnd of program."; }
22
23

Example of Exception Handling


#include <iostream>
using namespace std;
int main() {
int n1,n2,result;
cout<<"Enter 1st number : ";
cin>>n1;
cout<<"Enter 2nd number : ";
cin>>n2;
try {
if(n2==0) throw n2; //Statement 1
else {
result = n1 / n2;
cout<<"The result is : "<<result;
}
} catch(int x)
{ cout<<"Can't divide by : "<<x;
} cout<<"\nEnd of program."; }
24
25
26

Example Continued
27

Exercise

• Modify the above program to handle following


exceptions using multiple catch blocks (Refer:
Sample snapshot)
• 1. Exception : Division by zero
• 2. Exception: Division is less than 1
• 3. Exception : Unknown
28

Rethrowing Exceptions

• Rethrowing exception is possible, where we have an inner and outer try-catch


statements (Nested try-catch).
• An exception to be thrown from inner catch block to outer catch block is called
rethrowing exception.
Syntax of Rethrowing Exceptions 29
Example 30
#include <iostream>
using namespace std;
int main()
{ int a=1;
try {
try {
throw a;
}
catch(int x) {
cout<<"\nException in inner try-catch block.";
throw x; }
}
catch(int n) {
cout<<"\nException in outer try-catch block.";
}
cout<<"\nEnd of program.";
}
31
32

C++ Standard Exceptions

• C++ provides a list of standard exceptions defined in <exception> which we can use in
our programs.
• These are arranged in a parent-child class hierarchy.
• C++ provides a range of built in exceptions. The base class for all exceptions classes is
exception
33

C++ Standard Exceptions


34

C++ Standard Exceptions


35

C++ Standard Exceptions Continued


Example 36
#include <iostream>
catch(bad_alloc) //exception handler
using namespace std;
{
int main()
cout << “\nbad_alloc exception: can’t allocate
{
memory.\n”;
const unsigned long SIZE = 10000; //memory size
return(1);
char* ptr; //pointer to memory
}
try
delete[] ptr; //deallocate memory
{
cout << “\nMemory use is successful.\n”;
ptr = new char[SIZE]; //allocate SIZE bytes
return 0;
}
}
37

Exception Handling and Inheritance

• In inheritance, while throwing exceptions of derived classes, care should be taken


that catch blocks with base type should be written after the catch block with
derived type.
• Otherwise, the catch block with base type catches the exceptions of derived class
types too.
Example 38
#include <iostream>
using namespace std;
class Base {};
class Derived : public Base {};
int main() {
try {
throw Derived(); }
catch(Base b) {
cout<<"Base object caught"; }
catch(Derived d) {
cout<<"Derived object caught"; }
return 0;
}
39
40
41

Exception Handling and Inheritance

• In the previous program even though the exception thrown is of the type Derived
it is caught by the catch block of the type Base.
• To avoid that we have to write the catch block of Base type at last in the sequence
Example 42

#include <iostream>
using namespace std;
class Base {};
class Derived : public Base {};
int main() {
try {
throw Derived(); }
catch(Derived d) {
cout<<"Derived object caught"; }
catch(Base b) {
cout<<"Base object caught"; }
return 0; }
43
44

Case Studies on Exception Handling


Example-1 45
#include <iostream>
void getdist() //get length from user
using namespace std;
{
class Distance
cout << "\nEnter feet:" ;
{ private:
cin >> feet;
int feet;
cout << "Enter inches:" ;
float inches;
cin >> inches;
public:
if(inches >= 12.0) //if inches too big,
Distance() //constructor (no args)
throw "inches value is too large."; //throw
{ feet = 0; inches = 0.0; }
exception
}
Distance(int ft, float in) //constructor (two args)
{
void showdist() //display distance
if(in >= 12.0) //if inches too big,
{ cout << feet << "-" << inches; }
throw "inches value is too large."; //throw exception
};
feet = ft;
inches = in;
}
46
int main()
{
try Enter feet:12
{
Distance dist1(17, 3.5); //2-arg constructor Enter inches:22
Distance dist2; //no-arg constructor

dist2.getdist(); //get distance from user


//display distances
cout << "\ndist1 = "; Initialization error:inches value is too large.
dist1.showdist();
cout << "\ndist2 =";
dist2.showdist();
}
catch(const char *str) //catch exceptions
{
cout << "Initialization error:"<<str;
}
cout << endl;
return 0;}
Example-2 47
void display() const //display the String
#include <iostream> { cout << str; }
using namespace std;
#include <string.h>
#include <stdlib.h> String operator + (String ss) const //add Strings
const int SZ=50; {
class String //user-defined string type String temp; //make a temporary String
{ if( strlen(str) + strlen(ss.str) < SZ )
private: {
char str[SZ]; //holds a string strcpy(temp.str, str); //copy this string to temp
public: strcat(temp.str, ss.str); //add the argument string
}
String() else
{ strcpy(str, ""); } { throw 1;}
return temp; //return temp String
String( const char s[]) { }
if( strlen(s)>80)
throw "String Overflow";
strcpy(str, s);
}
48
int main() catch(const char* str)
{ {
cout<<"Initialization Error -"<<str;
try{ }
String s1("\nMerry Christmas!"); catch(int i)
String s2("Happy new year!“); {
String s3; //uses constructor 1 cout<<"Concatenation cannot be performed, string overflow";
s1.display(); //display strings }
s2.display(); return 0;
s3 = s1 + s2; //add s2 to s1, }
s3.display(); //display s3
cout << endl;
OUTPUT
String s4("What a wonderful day it is!!!!, Enjoy!!!!!"); Merry Christmas!Happy new year!
String s5; Merry Christmas!Happy new year!
s5=s3+s4; Concatenation cannot be performed, string overflow
s5.display();
}
49

References

• https://www.slideshare.net/AdilAslam4/exception-handling-in-c-69353237
• https://www.tutorialspoint.com/cplusplus/pdf/cpp_exceptions_handling.pdf
• C, the complete reference Book by Herbert Schildt

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy