C plus plus Notes
.png)
Basics of C plus plus
.png)
Basics Of OOPs
.png)
Classes and Objects
.png)
Polymorphism and Inheritence
.png)
Exception Handling
.png)
File Handling and templates
Heading
Q
1
Compare and contrast error and exception.

Ans
Exceptions are those which can be handled at the run time whereas errors cannot be handled.
An exception is an Object of a type deriving from the System.Exception class. SystemException is thrown by the CLR (Common Language Runtime) when errors occur that are nonfatal and recoverable by user programs. It is meant to give you an opportunity to do something with throw statement to transfer control to a catch clause in a try block.
Exception syntax:
try
{
//write your code here
}
Catch (exception type)
{
//writ your code here
}
An Error is something that most of the time you cannot handle it. Errors are unchecked exception and the developer is not required to do anything with these. Errors normally tend to signal the end of your program, it typically cannot be recovered from and should cause you exit from current program. It should not be caught or handled.
All the Errors are Exceptions but the reverse is not true. In general Errors are which nobody can control or guess when it happened, on the other hand Exception can be guessed and can be handled.

Q
2
What is a user defined exception. Wirte down the scenario where we require user defined exceptions.

Ans
Let's see the simple example of user-defined exception in which std::exception class is used to define the exception.
#include <iostream>
#include <exception>
using namespace std;
class MyException : public exception{
public:
const char * what() const throw()
{
return "Attempted to divide by zero!\n";
}
};
int main()
{
try
{
int x, y;
cout << "Enter the two numbers : \n";
cin >> x >> y;
if (y == 0)
{
MyException z;
throw z;
}
else
{
cout << "x / y = " << x/y << endl;
}
}
catch(exception& e)
{
cout << e.what();
}
}
Output:
Enter the two numbers :
10
2
x / y = 5

Q
3
When do we need multiple catch blocks for a single try block? Give an example.

Ans
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 short or long etc. Let's see the use of multiple catch blocks with an example.
Example:-
#include<iostream>
using namespace std;
int main()
{
int a=10, b=0, c;
try
{
//if a is divided by b(which has a value 0);
if(b==0)
throw(c);
else
c=a/b;
}
catch(char c) //catch block to handle/catch exception
{
cout<<"Caught exception : char type ";
}
catch(int i) //catch block to handle/catch exception
{
cout<<"Caught exception : int type ";
}
catch(short s) //catch block to handle/catch exception
{
cout<<"Caught exception : short type ";
}
cout<<"\n Hello";
}
Output :-
Caught exception : int type
Hello
