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

Exception Handling

The document discusses exception handling in C++. It defines exceptions as runtime anomalies or abnormal conditions encountered during program execution. C++ provides try, throw, and catch keywords to handle exceptions. try represents code that can throw exceptions, throw throws exceptions, and catch handles exceptions. Exceptions allow separation of error handling code and grouping of error types. The document provides examples of using try, throw, and catch blocks to handle exceptions in C++ programs.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
69 views

Exception Handling

The document discusses exception handling in C++. It defines exceptions as runtime anomalies or abnormal conditions encountered during program execution. C++ provides try, throw, and catch keywords to handle exceptions. try represents code that can throw exceptions, throw throws exceptions, and catch handles exceptions. Exceptions allow separation of error handling code and grouping of error types. The document provides examples of using try, throw, and catch blocks to handle exceptions in C++ programs.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 23

Exception Handling

By Pradeep Deshpande
Dept. of ISE, BLDEACET
Introduction
• One of the advantages of C++ over C is Exception Handling.
• Exceptions are runtime anomalies or abnormal conditions that a
program encounters during its execution.
• There are two types of exceptions:
a)Synchronous,
b)Asynchronous (i.e., exceptions which are beyond the program’s
control, such as disc failure, keyboard interrupts etc.).
C++ provides the following specialized keywords for this purpose:

• try: Represents a block of code that can throw an exception.

• catch: Represents a block of code that is executed when a particular


exception is thrown.

• throw: Used to throw an exception. Also used to list the exceptions


that a function throws but doesn’t handle itself.
Why Exception Handling? 
1) Separation of Error Handling code from Normal Code

2) Functions/Methods can handle only the exceptions they choose

3) Grouping of Error Types


C++ Exceptions
• When executing C++ code, different errors can occur:
• coding errors made by the programmer,
• errors due to wrong input, or
• other unforeseeable things.
• When an error occurs, C++ will normally stop and generate an error
message.
• The technical term for this is: C++ will throw an exception (error).
C++ try and catch
• Exception handling in C++ consists of three keywords: try, throw and
catch:
• The try statement allows you to define a block of code to be tested
for errors while it is being executed.
• The throw keyword throws an exception when a problem is detected,
which lets us create a custom error.
• The catch statement allows you to define a block of code to be
executed if an error occurs in the try block.
• The try and catch keywords come in pairs:

• We use the try block to test some code: If the value of a variable “age” is less
than 18, we will throw an exception, and handle it in our catch block.

• In the catch block, we catch the error if it occurs and do something about it.
The catch statement takes a single parameter. So, if the value of age is 15 and
that’s why we are throwing an exception of type int in the try block (age), we
can pass “int myNum” as the parameter to the catch statement, where the
variable “myNum” is used to output the value of age.

• If no error occurs (e.g. if age is 20 instead of 15, meaning it will be greater


than 18), the catch block is skipped.
#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;
}
•  There is a special catch block called the ‘catch all’ block, written as catch(…), that can be
used to catch all types of exceptions. For example, in the following program, an int is
thrown as an exception, but there is no catch block for int, so the catch(…) block will be
executed. 
#include <iostream>
using namespace std;

int main()
{
try {
throw 10;
}
catch (char *excp) {
cout << "Caught " << excp;
}
catch (...) {
cout << "Default Exception\n";
}
return 0;
}
• 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 the char.  

#include <iostream>
using namespace std;

int main()
{
try {
throw 'a';
}
catch (int x) {
cout << "Caught ";
}
return 0;
}
• In C++, try/catch blocks can be nested. Also, an exception can be re-
thrown using “throw; “.
#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;
}
• When an exception is thrown, all objects created inside the enclosing try block
are destroyed before the control is transferred to the catch block.
#include <iostream>
using namespace std;

class Test {
public:
Test() { cout << "Constructor of Test " << endl; }
~Test() { cout << "Destructor of Test " << endl; }
};

int main()
{
try {
Test t1;
throw 10;
}
catch (int i) {
cout << "Caught " << i << endl;
}
}
Quiz
What is the output of following program
#include <iostream>
using namespace std;
int main()
{
int x = -1;
try {
cout << "Inside try n";
if (x < 0)
{
throw x;
cout << "After throw n";
}
}
catch (int x ) {
cout << "Exception Caught n";
}

cout << "After catch n";


return 0;
}
What is the advantage of exception handling ?
• Remove error-handling code from the software's main line of code.
• A method writer can choose to handle certain exceptions and
delegate others to the caller.
• An exception that occurs in a function can be handled anywhere in
the function call stack.
What should be put in a try block?
1. Statements that might cause exceptions
2. Statements that should be skipped in case of an exception
Output of the following program?
#include<iostream>
using namespace std;

class Base {};


class Derived: public Base {};
int main()
{
Derived d;
try {
throw d;
}
catch(Base b) {
cout<<"Caught Base Exception";
}
catch(Derived d) {
cout<<"Caught Derived Exception";
}
return 0;
}
Output of the following program?
#include <iostream>
using namespace std;

int main()
{
try
{
throw 'a';
}
catch (int param)
{
cout << "int exceptionn";
}
catch (...)
{
cout << "default exceptionn";
}
cout << "After Exception";
return 0;
}
Output of the following program?
#include <iostream>
using namespace std;
int main()
{
try
{
throw 10;
}
catch (...)
{
cout << "default exceptionn";
}
catch (int param)
{
cout << "int exceptionn";
}
return 0;
}
Output of the following program?
#include <iostream>
using namespace std;
int main()
{
try
{
try
{
throw 20;
}
catch (int n)
{
cout << "Inner Catchn";
throw;
}
}
catch (int x)
{
cout << "Outer Catchn";
}
return 0;
}
Output of the following program?
#include <iostream>
using namespace std;

class Test {
public:
Test() { cout << "Constructing an object of Test " << endl; }
~Test() { cout << "Destructing an object of Test " << endl; }
};

int main() {
try {
Test t1;
throw 10;
} catch(int i) {
cout << "Caught " << i << endl;
}
}
#include <iostream>
using namespace std;
class Test {
static int count;
int id;
public:
Test() {
count++;
id = count;
cout << "Constructing object number " << id << endl;
if(id == 4)
throw 4;
}
~Test() { cout << "Destructing object number " << id << endl; }
};

int Test::count = 0;
int main() {
try {
Test array[5];
} catch(int i) {
cout << "Caught " << i << endl;
}
}
Which of the following is true about
exception handling in C++?
1) There is a standard exception class like Exception class in Java.
2) All exceptions are unchecked in C++, i.e., compiler doesn't check if
the exceptions are caught or not.
3) In C++, a function can specify the list of exceptions that it can throw
using comma separated list like following.
void fun(int a, char b) throw (Exception1, Exception2, ..)

You might also like