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

Object Oriented Programming (Oop) With C++: Exceptions and String

This document discusses exception handling in C++ and string manipulation. It defines exceptions as runtime errors or unusual conditions that occur during program execution. It describes how to handle exceptions using try, catch, and throw blocks. It also covers the string class in C++ and how to manipulate strings using functions like assign(), resize(), compare(), erase(), and swap().

Uploaded by

ANIK Dey
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views

Object Oriented Programming (Oop) With C++: Exceptions and String

This document discusses exception handling in C++ and string manipulation. It defines exceptions as runtime errors or unusual conditions that occur during program execution. It describes how to handle exceptions using try, catch, and throw blocks. It also covers the string class in C++ and how to manipulate strings using functions like assign(), resize(), compare(), erase(), and swap().

Uploaded by

ANIK Dey
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

OBJECT ORIENTED PROGRAMMING (OOP) WITH C++

EXCEPTIONS AND STRING

AIUB. FALL 2017

Dr. Mahbubul Syeed


Associate Professor, Department. of CS, AIUB
[email protected]
www.msyeed.weebly.com
CONTENTS

ü Define exception, distinction between exception and compile time error.


ü Handling exceptions in c++
ü Use of try, catch, throw in handing exceptions.
ü Default and multiple catch blocks, nested try blocks.
ü User defined exception using exception class.

ü String class in C++.


ü Manipulating strings using String library functions.
STRING CLASS
STRING

¡ Strings are objects that represent sequences of characters.


¡ Best Source: http://www.cplusplus.com/reference/string/string/
#include <iostream> STRING: CAPACITY
#include <string>
using namespace std;

int main ()
{
string str ("Test string"); // string is a class. So we can initialize it with the constructor.
// str = "Test string"; // other way of doing the same initiaization.
cout << "size: " << str.size() << "\n"; // current size (in on of characters)
cout << "length: " << str.length() << "\n"; // current length (in no of characters)
cout << "capacity: " << str.capacity() << "\n"; // current capacity of the string
cout << "max_size: " << str.max_size() << "\n"; // shows the max size that a string could have
if(!str.empty()) //Test if string is empty
cout << "String is not empty!\n"; size: 11
length: 11
str.clear(); // Erase the content of an string capacity: 11
std::cout <<"Ater erasing: " << str << "\n"; max_size: 4611686018427387897
String is not empty!
if(str.empty()) cout << "String is empty!"; Ater erasing:
String is empty!
return 0;
}
#include <iostream>
STRING : RESIZING THE STRING
#include <string>
using namespace std;
int main ()
{
string str ("I like to code in C");
cout << str << '\n';

unsigned sz = str.size();
I like to code in C
Current size: 19
cout << "Current size: " << sz << '\n';
I like to code in C++
Current size: 21
str.resize (sz+2,'+'); I like to code
cout << str << '\n';
cout << "Current size: " << str.size() << '\n';

str.resize (14);
cout << str << '\n';
return 0; 6

}
#include <iostream>
#include <string>
STRING : MANIPULATION (ASSIGN() FUNCTION)
int main ()
{
std::string str;
std::string base="The quick brown fox jumps over a lazy dog.";

str.assign(base);
std::cout << str << '\n';

str.assign(base,10,9);
std::cout << str << '\n'; // "brown fox"
The quick brown fox jumps over a lazy dog.
str.assign("pangrams are cool",7); brown fox
std::cout << str << '\n'; // "pangram"
pangram
str.assign("c-string"); c-string
std::cout << str << '\n'; // "c-string"
**********
str.assign(10,'*'); ----------
std::cout << str << '\n'; // "**********” fox jumps over
str.assign<int>(10,0x2D);
std::cout << str << '\n'; // "----------"

str.assign(base.begin()+16,base.end()-12);
std::cout << str << '\n'; // "fox jumps over" 7

return 0;
}
STRING : MANIPULATION
#include<string>
int main()
{
string s1="Hello ";
string s2=“Good morning"; Output:
string s3="Bad"; Good Hello morning
Good Happy morning
s2.insert(5,s1);
Good badappy morning
cout<<s2<<endl;
Good morning
s2.replace(5,5,"happy ");
cout<<s2<<endl;
s2.replace(5,1,s3);
cout<<s2<<endl;
s2.erase(5,8);
cout<<s2<<endl;

return 0;
}
8
STRING : MANIPULATION
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string s1("hello");
string s2("hello good morning");
string s3("Hello");
string s4("hello");
Output:
s1 and s4 are same
// compare() function is used to determine the similarity between strings.
s1 and s3 are not same
if(s1.compare(s4) == 0)
cout << "s1 and s4 are same \n";
-13
if(s1.compare(s3) != 0)
13
cout << "s1 and s3 are not same \n";

int x=s1.compare(s2);
cout<<x<<endl;
cout<<s2.compare(s1)<<endl;
}
9
STRING : MANIPULATION
#include <iostream>
#include <string>
using namespace std;

int main ()
{
string s1("hello world");

s1.erase(7); //erase chars starting from index 7


hello w
cout<<s1 << endl;
s1.erase(); //erase all characters
s1 is now empty
if(s1.empty()) cout << "s1 is now empty \n";
Before Swapping: Big and Boss
After Swapping: Boss and Big
string s2("Big");
string s3("Boss");
cout << "Before Swapping: " << s2 << " and " << s3 << endl;
s2.swap(s3); // swap the contents between two given string objects
cout << "After Swapping: " << s2 << " and " << s3 << endl;

return 0; }
EXCEPTION HANDLING
EXCEPTION

¡ Exceptions are runtime anomalies or an unusual condition that a program may face.
¡ Exceptions are not syntax error nor logical error.
EXCEPTION - EXAMPLE

Divide by zero error or warning!

#include <iostream> No compiler error!


using namespace std;
int main() {
Warning! Divide by zero!
int numerator = 10, denominator = 0;
int ans = numerator / denominator;
Program terminating abnormally!!
cout << "Result is: " << ans << endl;
Terminates where the runtime error occurs!!
cout << "Program is running normal!!";
return 0;
}
EXCEPTION - EXAMPLE
Bad memory allocation exception!

#include <iostream>
using namespace std;
int main() {
No compiler error!
int *arr = new int[1000000000];
cout<< "This is other output"; Warning! Array index out of bound or index not initialized!
return 0;
} Program terminating abnormally!!
EXCEPTION – HANDLING EXCEPTIONS

Try{}: represents a block of code that can throw an exception.

throw: Used to throw an exception.

Also used to list the exceptions that a function throws, but doesn’t handle itself.

Catch{}: represents a block of code that is executed when a particular exception is thrown.
EXCEPTION – HANDLING EXCEPTIONS

Try{
// check the code that might cause runtime exception and throw appropriate exception
if(CHECK_FOR_ERROR) throw SOME_EXCEPTION;
}
catch (RECEIVE SOME_EXCEPTION)
{
//code to handle the exception
}

//rest of the code runs as normal…..


#include <iostream>
using namespace std;
int main() {
int numerator = 10, denominator = 0; • Put your code inside try{} block that might throw exception.
try{
• Check exception condition with if statement and use throw clause
if(denominator == 0)
to throw an exception if exception occurs!
throw string("Divide by zero exception!”);
int ans = numerator / denominator; • Write appropriate catch(){} block to accept the thrown exception
cout << "Result is: " << ans << endl; and handle it appropriately.
}
catch(string s){
cout << s << endl;
}
cout << "Program is running normal!!"; Divide by zero exception!
return 0; Program is running normal!!
}
#include <iostream>
using namespace std;
int main() {
int *arr;
try{
arr = new int[1000000000];
}
catch (const std::bad_alloc& ba) {
cout << "Exception is: " << ba.what() << endl; Exception is: std::bad_alloc
This is other output
}
cout<< "This is other output";
return 0;
}
MULTIPLE CATCH BLOCK

¡ A try block must be followed by at least one catch block (otherwise compiler error occurs).
¡ If there are more than one catch block then the catch which meets the data type is executed.
¡ If there is no catch for a corresponding throw then following system functions are called.
Terminate() -> abort()
int main()
{
int m;
cin>>m;
try { input output
if(m==0) throw m;
cout<<200/m<<endl; 66
3
}
end
catch(int x)
{ exception occurred for: 0
0
cout<<"exception int occured for:"<<x<<endl; end
}
catch(double d)
{
cout<<"exception for double"<<d<<endl;
}
cout<<"end\n";
return 0;
}
CATCHING ALL EXCEPTIONS

catch(…)
{
cout<<“catching all data types\n”;
}
q This special catch block should be the last among all catch blocks in a try-catch family.
int main()
{
int m;
cin>>m;
try {
if(m==0) throw m;
else throw ‘a’;
input output
}
3 exception for all
catch(int x)
end
{
cout<<"exception int occured for:"<<x<<endl;
0 exception occurred for: 0
}
end
catch(…)
{
cout<<"exception for all”<<endl;
}
cout<<"end\n";
return 0;
}
void test(int x) Invoking function that generates exception
{
if(x==0) throw 1;
if(x==1) throw 1.0;
throw 'x';
} input Output
int main()
{
int n; 0 Catch all
cin>>n; end
try{
test(n); 5 Catch all
cout<<"exiting try\n"; end
}
catch(...)
{
cout<<"catch all\n";
}
cout<<"end\n";
return 0;
}
void test(int x) RE-THROWING AN EXCEPTION
{
try{
if(x==0) throw 1;
else throw 1.0;
} Input output
catch(int m) { throw; }
catch(...) { cout<<"all\n"; } 0 In int main
} end
int main()
1 all
{
int n; exiting try
cin>>n; End
try{
test(n);
cout<<"exiting try\n";
}
catch(int n) { cout<<"in int main\n"; }
catch(...) { cout<<"catch all\n"; }
cout<<"end\n";
return 0;
}
WRITING MY OWN EXCEPTION CLASS
#include <iostream>
#include <exception>
using namespace std;

struct MyException : public exception {


const char * what () const throw () {
return "C++ Exception"; }
};

int main() { MyException caught


int i = 5; C++ Exception
try {
if(i != 0) throw MyException();
}
catch(MyException& e) {
std::cout << "MyException caught" << std::endl;
std::cout << e.what() << std::endl;
}
catch(std::exception& e) {
//Other errors }
}

You might also like