You are on page 1of 20

EC-212 OOP

LECTURE 12
Exception

 An exception is a problem that arises during the


execution of a program.
 A C++ exception is a response to an exceptional
circumstance that arises while a program is running, such
as
 an attempt to divide by zero.
 Array over flow
 Exception Handling provide a way to transfer control
from one part of a program to another.
Exception Handling

 Exception handling provide a way to transfer control


from one part of a program to another without crashing
the program execution
 C++ exception handling is built upon three keywords: try,
catch, and throw.
Exception Handling

 Assuming a block will raise an exception, a method


catches an exception using a combination of
the try and catch keywords.
 A try/catch block is placed around the code that might
generate an exception.
 Code within a try/catch block is referred to as protected
code
Try, Catch, Throw

 throw − A program throws an exception when a problem


shows up. This is done using a throw keyword.
 catch − A program catches an exception with an
exception handler at the place in a program where you
want to handle the problem. The catch keyword
indicates the catching of an exception.
 try − A try block identifies a block of code for which
particular exceptions will be activated. It's followed by
one or more catch blocks.
Syntax

try {
// Block of code to try
throw exception; // Throw an exception when a problem arise
}
catch( ExceptionName e1 ) { // catch block }
catch( ExceptionName e2 ) { // catch block }
catch( ExceptionName eN ) { // catch block }

You can list down multiple catch statements to catch different type of
exceptions in case your try block raises more than one exception in
different situations.
Example

try {
int age = 15;
if (age > 18) {
cout << "Access granted - you are old enough.";
} else {
throw (age);
}
}
catch (int myNum) {
cout << "Access denied - You must be at least 18 years old.\n";
cout << "Age is: " << myNum;
}
Example
try {
int age = 15;
if (age > 18) {
cout << "Access granted - you are old enough.";
} else {
throw 505;
}
}
catch (int myNum) {
cout << "Access denied - You must be at least 18 years old.\n";
cout << "Error number: " << myNum;
}
Throwing Exceptions
 Exceptions can be thrown anywhere within a code block
using throw statement.
 The operand of the throw statement determines a type for the
exception and can be any expression and the type of the result of
the expression determines the type of exception thrown.

double division(int a, int b) {


if( b == 0 ) {
throw "Division by zero condition!";
}
return (a/b);
}
Catching Exceptions
 The catch block following the try block catches any exception.
 You can specify what type of exception you want to catch and this
is determined by the exception declaration that appears in
parentheses following the keyword catch.

try {
// protected code
} catch( ExceptionName e ) {
// code to handle ExceptionName exception
}
Example

double division(int a, int b) {


int main () { if( b == 0 ) {
int x = 50; throw "Division by zero condition!";
int y = 0; }
double z = 0; return (a/b);
}
try {
z = division(x, y);
cout << z << endl;
} catch (const char* msg) {
cerr << msg << endl;
}

return 0;
}
Example
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;
}
C++ Standard Exceptions
C++ Standard Exceptions
// bad_alloc standard exception
#include <iostream>
#include <exception>
using namespace std;

int main () {
try {
int* myarray= new int[1000];
}
catch (exception& e)
{
cout << "Standard exception: " << e.what() << endl;
}
return 0;
}
Define New Exceptions

int main() { class MyException : public exception {


try { Public:
throw MyException(); const char * what () {
} return "C++ Exception";
catch(MyException& e) { }
std::cout << "MyException caught" << };
std::endl;
std::cout << e.what() << std::endl;
} catch(std::exception& e) {
//Other errors
}
}
Class Task
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;
}
Class Task
int main()
{
try
{
throw 'a';
}
catch (int param)
{
cout << "int exception\n";
}
catch (...)
{
cout << "default exception\n";
}
cout << "After Exception";
return 0;
}
Exception & Inheritance
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;
}
Nested Try/Catch Blocks
 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; }
Summary: (Exception Handling)
 Exception handling in C++ is done using three keywords, Try,
Catch, Throw.
 Sophisticated technique to handle program crashes due to
runtime errors, separately provide error handling code in catch
block
 Multiple catch blocks immediately after try block possible.
 Default catch block (…) should appear in the last, otherwise
error -> making subsequent catch blocks redundant.

You might also like