0% found this document useful (0 votes)
193 views26 pages

Clas-PPT-C++-Exception Handling

The document discusses exception handling in C++. Exception handling allows a program to handle runtime errors and unexpected events gracefully. It describes the try, throw, and catch keywords used to handle exceptions and provides an example of exception handling code.

Uploaded by

Ext Codered
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)
193 views26 pages

Clas-PPT-C++-Exception Handling

The document discusses exception handling in C++. Exception handling allows a program to handle runtime errors and unexpected events gracefully. It describes the try, throw, and catch keywords used to handle exceptions and provides an example of exception handling code.

Uploaded by

Ext Codered
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/ 26

Exception Handling

What is exception?
• Exception in a C++ programs refers an unexpected circumstances like
runtime errors.

• So whenever an unexpected circumstance occurs, the program control is


transferred to special functions known as handlers.

• To catch the exceptions, you place some section of code under exception
inspection. The section of code is placed within the try-catch block.

• If an exceptional situation occurs within that section of code, an exception


will be thrown. Next, the exception handler will take over control of the
program.

• In case no exceptional circumstance occurs, the code will execute


normally. The handlers will be ignored.
Need of Exception Handling
• Exception handling in C++ provides you with a way of handling
unexpected circumstances like runtime errors.

• You will separate your error handling code from your normal
code.

• The code will be more readable and easier to maintain.

• Functions can handle the exceptions they choose.

• Even if a function throws many exceptions, it will only handle


some. The caller will handle the uncaught exceptions.
Exception Handling Tools
• Try– the try block identifies the code block for which certain
exceptions will be activated. It should be followed by one/more
catch blocks.

• Throw– when a program encounters a problem, it throws an


exception. The throw keyword helps the program perform the
throw.

• Catch– a program uses an exception handler to catch an exception.


It is added to the section of a program where you need to handle
the problem. It’s done using the catch keyword.
Property of try and Catch
• Content of a try block:
– try keyword will be there
– after that codes will be there enclosed by brackets
– The statements that cause exception
– The statements that should be skipped if the exception will
be occurred.

• At least one catch handler must immediately follow


each try block
• Content of catch block:
– catch is the keyword
– the specific exception parameter enclosed by a
parenthesis followed the catch key word.
Exception Handling Method
• Termination model of exception handler
– If an exception occurs as a result of a statement in a try block, the try block expires.
– Then the first catch block will be searched to handle the exception.
– A match occurs if the types are identical or if the thrown exceptions type is derived class
of the exception parameter types.
– When a match occurs the code contained in the matching catch handler executes.
– Program control does not return to that point where the exception is occurred.
– The control resumes with first statement after the last catch handler following try block.

• Resumption model of exception handler


– If an exception occurs as a result of a statement in a try block, the try block expires.
– Then the first catch block will be searched to handle the exception.
– A match occurs if the types are identical or if the thrown exceptions type is derived class
of the exception parameter types.
– When a match occurs the code contained in the matching catch handler executes.
– The control resumes just after the throw point.
Example of Exception Handling
#include <iostream>
using namespace std;
double divisionz(int x, int y) {
if( y == 0 ) {
throw "Division by zero condition!";
}
return (x/y);
}

int main () {
int m = 50;
int n;
double p = 0;
try {
cin>>n;
p = divisionz(m, n);
cout << p << endl;
}
catch (const char* msg) {
cerr << msg << endl;
}
return 0;
}
Example of Exception Handling
• Include the iostream header file in the program to use its functions.
• Include the std namespace in the program to its classes without calling it.
• Create a function named division that takes two integer arguments, x, and y. The function should
return a double result.
• Use an if statement to check whether the value of variable argument y is 0. The { marks the
beginning of if body.
• The message to be returned/thrown if y is 0.
• End of the body of the if statement.
• The zeroDivision function should return the value of x/y.
• End of the body of the zeroDivision function.
• Call the main() method. The { marks the beginning of this method.
• Declare an integer variable and assigning it the value 11.
• Declare an integer variable b and assigning it the value 0.
• Declare a double variable c and assigning it the value 0.
• Use the try statement to catch an exception. The { marks the beginning of the body of try/catch
block. The code added within the body will become the protected code.
• Call the zeroDivision function and passing to arguments a and b, that is, 11 and 0. The result of this
operation will be stored in variable c.
• Print out the value of variable c on the console.
• End of the body of try/catch block.
• Catch the exception. The returned error message will be stored in the variable message.
• Print out the returned error message on the console.
• End of the body of the catch block.
• The program should return a value upon successful execution.
• End of the main() function body.
#included <iostream.h>
using namespace std;
void fun1(){
//body of the function
throw exception1;
}

int main(){
try{
fun1();
//body not want to print if the exception occur
}
catch(//type1){
//body to handle the exception
}

catch(//type2){
//body to handle the exception
}

catch(//type3){
//body to handle the exception
}

catch(//type4){
//body to handle the exception
}
chtch(…){
}
return 0;
}
Rethrowing
• An exception handler can process an exception or can not process that.
• In that case the exception handler refer the exception to another
exception handler.
• This can be achieved by rethrowing the exception.
• That can be done by the statement
– throw;
• The rethrown exception is detected by next enclosing try block.
• When an exception is rethrown that can be handled by the catch listed
after the try block.
• If an empty throw statement is there outside of a catch handler the
functions terminate. Then abandons exception processing terminates the
program immediately.
struct E { try{
const char* message; cout<<"In the try outside the main"<<endl;
E() : message("Class E") { } throw;
}; }
catch (...) {
struct E1 : E { cout << "In handler of catch (...) outside main in catch
const char* message; 2nd" << endl;
E1() : message("Class E1") { } }
};
}

struct E2 : E { int main() {


const char* message;
E2() : message("Class E2") { } /*try{
}; cout<<"In the try outside the main"<<endl;
}
catch (...) {
void f() { cout << "In handler of catch (...) outside main" << endl;
try { }*/
cout << "In try block of f()" << endl;
cout << "Throwing exception of type E1" << endl; try {
E1 myException; cout << "In try block of main()" << endl;
throw myException; f();
} }
catch (E2& e) { catch (E2& e) {
cout << "In handler of main(), catch (E2& e)" << endl;
cout << "In handler of f(), catch (E2& e)" << endl;
cout << "Exception: " << e.message << endl;
cout << "Exception: " << e.message << endl;
}
throw; catch (...) {
} cout << "In handler of main(), catch (...)" << endl;
catch (E1& e) { }
cout << "In handler of f(), catch (E1& e)" << endl;
cout << "Exception: " << e.message << endl; /*try{
throw; cout<<"In the try outside the main"<<endl;
} throw;
catch (E& e) { }
catch (...) {
cout << "In handler of f(), catch (E& e)" << endl;
cout << "In handler of catch (...) outside main in catch
cout << "Exception: " << e.message << endl;
2nd" << endl;
throw; }*/
}
}
Call ‘terminate’
• Cases of terminate calling:
– An exception does not find a match catch
– A destructor attempts to throw an exception during stack unwinding
– A rethrow is called when no exception is handled
– Calling of function unexpected due to exception mismatch

• terminate call is default to stop the execution of an program.

• During the calling of terminate function set_terminate specify the function


to invoke or terminate itself call abort

• Resource leak: Aborting a program component due to an uncaught


exception could leave a resource (file stream, IO device) in such a state
that other program are not able to use that.
Stack Unwinding
• Function-call stack unwound when exception thrown
and not caught in a particular scope
• How it will be resolved:
– Tries to catch exception in next outer try/catch block
– Function in which exception was not caught terminates
• Local variables destroyed
• Control returns to place where function was called
– If control returns to a try block, attempt made to catch exception
• Otherwise, further unwinds stack
– If exception not caught, terminate called
Constructor–Destructor
Exception Handling
• Exception thrown by a constructor cause calling of an destructor for any
object that is built partly (built before calling occurring an exception)
• Each automatic object constructed in a try block is destructed before an
exception is thrown.
• Stack unwinding completes before an exception handler begins executing.
• If an object has member objects and if an exception is thrown before the
outer object is constructed, the destructor will work for that part of the
object that is constructed before occurring the exception.
• The destructor for the array element object will be called if an exception
occurs during the creation of the array.
• When an exception is thrown from the constructor for an object that is
created in a new exception, the dynamically allocated memory will be
free.
Thrown exceptions in
constructors
• Cases:
– Destructors called for all completed base-class objects and member
objects before exception thrown.

– If the destructor that is originally called due to stack unwinding ends


up throwing an exception, terminate called.

– If object has partially completed member objects when exception


thrown, destructors called for completed objects.
#include <iostream>
using namespace std;

// Initialization of class
class Test {
public:
// Constructor of class
Test()
{
cout << "Constructing an object of class Test "<< endl;
}

// Destructor of class
~Test()
{
cout << "Destructing the object of class Test "<< endl;
}
};

int main()
{
try {
// Calling the constructor
Test t1;
throw 10;

} // Destructor is being called here


// Before the 'catch' statement
catch (int i) {
cout << "Caught " << i << endl;
}
}
#include <iostream>
using namespace std;

class Test {
static int count; // Used static to initialise the scope
// Of 'count' till lifetime
int id;

public:
// Constructor
Test()
{
count++;
id = count;
cout << "Constructing object number " << id << endl;
if (id == 4)
throw 4;
}
// Destructor
~Test()
{
cout << "Destructing object number " << id << endl;
}
};

int Test::count = 0;

// Source code
int main()
{
try {
Test array[5];
}
catch (int i) {
cout << "Caught " << i << endl;
}
}
Exception Specification
• If a throw statement has a list of exception types that means the function
can throw any one type of exception.
• Example:
int g( double h ) throw (Exception1, Exception2, Exception3)
{
// function body
}

• If the function throw an exception that does not match with the type then
function unexpected will be called and the program will be terminated.
• If a function doesn’t have any exception then it can throw any exception.
(syntax: throw())
• Some compiler ignore exception specification.
Exception & Inheritance
• Different exception class can be derived from common base class.

• In C++ standard library there is a base class exception which has a virtual
function what that will help us to return error message (returns the error
message of an exception object ).

• runtime_error, is derived class of exception which can handled the


exception of division by zero.

• If catch can get a pointer/reference to a base class, can also catch


pointers/references to derived classes
Processing ‘new’ failures
• new: To acquire memory

• A new handler function should either:


– Make more memory available by deleting other dynamically allocated memory and
return to the loop in operator new
– Throw an exception of type bad_alloc
– Call function abort or exit (header <cstdlib>) to terminate the program

• Method:
– new returns 0, abort, does not allow program to recover
– new throws bad_alloc exception
– use new(nothrow) instead of new to have new return 0 when it fails.

• new(notthor)
– Function set_new_handler(functionName) sets which function is
called when new fails.
– Function can return no value and take no arguments
– new will not throw bad_alloc
Exception Hierarchy
Standard Exception
Exception Description

This is an exception and the parent class of all standard C++


std::exception
exceptions.

std::bad_alloc This exception is thrown by a new keyword.

std::bad_cast This is an exception thrown by dynamic_cast.

A useful device for handling unexpected exceptions in C++


std::bad_exception
programs.

std::bad_typeid An exception thrown by typeid.

std::logic_error This exception is theoretically detectable by reading code.

This is an exception thrown after using a mathematically invalid


std::domain_error
domain.

std::invalid_argument An exception thrown for using invalid arguments.

std::length_error An exception thrown after creating a big std::string.

std::out_of_range Thrown by at method.

std::runtime_error This is an exception that cannot be detected via reading the code.

This exception is thrown after the occurrence of a mathematical


std::overflow_error
overflow.

This exception is thrown when you attempt to store an out-of-


std::range_error
range value.

An exception thrown after the occurrence of mathematical


std::underflow_error
underflow.
Define an Exception
• The C++ std::exception class allows us to define objects that can be
thrown as exceptions.

• This class has been defined in the <exception> header.

• The class provides us with a virtual member function named what.

• This function returns a null-terminated character sequence of type


char *.

• We can overwrite it in derived classes to have an exception


description.
#include <iostream>
#include <exception>
using namespace std;
class newException : public exception {
virtual const char* what() const throw() {
return "newException occurred";
}
} newex;

int main() {
try {
throw newex;
}
catch (exception& ex) {
cout << ex.what() << '\n';
}
return 0;
}
Explanation
• Include the iostream header file in our program. We will use its functions without getting errors.
• Include the exception header file in our program. We will use its functions like what without errors.
• Include the std namespace in our program to use its classes without calling it.
• Create a new class named newException. This class inherits the exception class of C++.
• The beginning of the class body.
• Overwrite the virtual member function what() defined in the exception header file. We will then
describe our own exception, the new exception.
• Start the definition of the new exception.
• The message to be returned if the new exception is caught.
• End of the definition of the new exception.
• End of the body of class newException. The newex is the name to be used to catch our new
exception, after which the newException will be called.
• Call the main() function. The program logic should be added within its body. The { marks the
beginning of its body.
• Use a try statement to mark the code within which we need to mark the exception. The { marks the
beginning of the body of try/catch block. The code surrounded by this will become protected.
• Throw the newex exception if it’s caught.
• End of the try body.
• Use the catch statement to catch the exception. The exception error message will be stored in
variable ex.
• Print the exception error message on the console.
• End of the body of catch statement.
• The program should return a value if it executes successfully.
• End of the body of the main() function.
Thank You

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