0% found this document useful (0 votes)
17 views29 pages

PPT12 Exception Handling

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)
17 views29 pages

PPT12 Exception Handling

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/ 29

UTA 018: OOPs

Exception Handling

1
What is Exception Handling?

Exception handling is a mechanism in C++ to handle runtime errors or


"exceptions" that may occur during the execution of a program. These
exceptions could include invalid user input, divide-by-zero errors,
memory allocation failures, file I/O errors, etc.
Exception Handling Motivation
The motivation behind exception handling is to:

• Separate error-handling code from the main logic of the program.

• Increase robustness: Handle errors gracefully without crashing the program.

• Provide a way to recover from unforeseen runtime conditions.

• Without proper error handling, programs can terminate abruptly, leading to poor user experiences and

system instability.

• Exception is a run-time error, such as divide by zero, array out of bounds, file not found etc.

• It helps to continue the normal flow of the application even in the case of runtime errors

• It makes the code simpler, cleaner, and less likely to miss errors
Exception Handling Mechanism

Try Block Exception


Catch Block
Object
Detects and Catches and
Throws Handles
Exception Exception
Basic Syntax of Exception Handling
C++ provides a structured way to handle exceptions using three main keywords:
• try: Block of code that may throw an exception.
• throw: Used to throw an exception when an error occurs.
• catch: Block of code that handles the exception.
try {
// Code that may cause an exception
if (/* some error condition */) {
throw exception; // Throw an exception
}
}
catch (type_of_exception) {
// Code to handle the exception
}
try{
fun1();
fun2();
fun3();
} catch(error){
// … do something if error happens in any of the functions
}
// if any of the fun() is a constructor then you have to use if-else in the
constructor to handle the error since it cannot return anything, which
is not neat practice.
Exception thrown and caught
• Exception is thrown at runtime.
• If an exception is not handled (caught), it prints exception
message and terminates the program.
• Programmer’s job is to handle possible exceptions using try,
throw and catch to avoid abnormal program termination
Catching Multiple Exceptions
#include <iostream> catch (int e) {
using namespace std; cout << "Caught an integer: " << e << endl;
}
int main() { catch (float e) {
try { cout << "Caught a float: " << e << endl;
int choice; }
cout << "Enter choice (1 for int, 2 for float): "; catch (const char* e) {
cin >> choice; cout << "Caught a string: " << e << endl;
if (choice == 1) }
throw 100;
else if (choice == 2) return 0;
throw 2.5f; }
else
throw "Invalid choice!";
}
Exception Handling with Class Objects
C++ allows you to throw and catch objects of user-defined types (classes). This is useful for passing detailed error
information.

int main() {
int numerator = 10, denominator = 0;
#include <iostream>
using namespace std; try {
if (denominator == 0) {
class DivisionByZero { DivisionByZero ex;
public: throw ex; // Throw an object of the class
void errorMessage() { }
cout << "Error: Division by zero!" << endl; cout << "Result: " << numerator / denominator << endl;
} }
}; catch (DivisionByZero ex) {
ex.errorMessage();
}

return 0;
}
Catching All Exceptions (catch(...))
C++ provides a special syntax to catch any type of exception. The catch(...) block acts as a catch-all handler and
can be used when the type of exception is unknown.

int main() {
#include <iostream>
using namespace std; try {
throw 10;
int main() {
}
try {
throw 10; catch (char *e) { cout << "Caught " << e; }
} catch (...) { cout << "Default Exception\n"; }
catch (...) { // Catch any type of exception
return 0;
cout << "Caught an unknown exception!" << endl;
} }

return 0;
}
// What will be the output?

int main() {
try {
throw "10";
}
catch (const char *e) { cout << "Caught " << e; }
catch (...) { cout << "Default Exception\n"; }

Output
Caught 10
Throwing Exceptions from Functions
#include <iostream>
using namespace std;

int divide(int a, int b) {


if (b == 0)
throw "Division by zero!";
return a / b;
}

int main() {
int x = 10, y = 0;

try {
cout << "Result: " << divide(x, y) << endl;
}
catch (const char* e) {
cout << "Error: " << e << endl;
}

return 0;
}
Multiple catch is possible
try {
//some code
throw exception;
}
catch(specific type exception) {//some code }

catch(generic type exception) { //some code }

Catch blocks must be ordered so that most specific exceptions get caught before generic exceptions.
Exception Specification
• C++ provides a mechanism to ensure that a given function is limited to throw only
a specified list of exceptions.

void translate() throw(unknown_word,bad_grammar) {


/* ... */
}
• It will not throw any exception other than unknown _word or bad_grammar
class unknown_word{};
class bad_grammar{};
void translate(int a) throw(unknown_word,bad_grammar) {
if (a==0) throw unknown_word();
else if(a==1) throw bad_grammar();
else throw 10;
}
int main(){
try{ translate(22);}
catch(unknown_word u){cout<<" unknown word";}
catch(bad_grammar g){cout<<" bad grammar";}
catch(...) {cout<<"Default catch";}
}
Output
terminate called after throwing an instance of 'int'

Aborted (core dumped)


Standard Library Exceptions in C++
In C++, exceptions can be thrown and handled using the
Standard Library Exceptions. These exceptions are part of the
<exception> and <stdexcept> headers and represent a collection of
predefined exception classes for common error conditions like runtime
errors, out-of-range errors, bad memory allocation, etc.

C++ provides these standard exception classes to help handle


specific types of errors more effectively and systematically. These
classes follow a hierarchy, with std::exception being the base class
from which all standard exceptions are derived.
Standard Exception Class Hierarchy
At the top of the hierarchy is the std::exception class, from which all other standard exception types are
derived. Below are the commonly used standard exception classes:

std::exception

std::logic_error std::runtime_error
+-- std::invalid_argument +-- std::range_error
+-- std::domain_error +-- std::overflow_error
+-- std::underflow_error
+-- std::length_error
+-- std::out_of_range
std::exception
Base Class for All Exceptions:-
std::exception is the base class for all standard exceptions. It
provides the virtual member function what() that returns an error
message.

You can catch any exception derived from std::exception by catching


a reference to std::exception.
Example
#include <iostream>
#include <exception> Output:
using namespace std; Caught exception: std::exception

int main() {
try {
throw std::exception();
}
catch (const std::exception& e) {
std::exception::what() returns a
cout << "Caught exception: " << e.what() << endl; generic message "std::exception"
}
return 0;
}
std::logic_error
• Std::logic_error is a derived class of std::exception used for errors in
the logic of the program (e.g., domain errors, invalid arguments).
• These errors represent conditions that could be prevented with
proper input validation.
Derived Classes:

• std::invalid_argument: Thrown when an argument is invalid.


• std::domain_error: Thrown when a mathematical domain error occurs.
• std::length_error: Thrown when an object exceeds its maximum size.
• std::out_of_range: Thrown when an attempt is made to access an element
outside the valid range.
Example
Example
Example
std::runtime_error

• Std::runtime_error is another derived class of std::exception and is


used for errors that occur during the runtime of the program.
• These errors cannot usually be predicted or checked at compile time.
Derived Classes:
• std::range_error: Thrown when a result of a computation is out of range.
• std::overflow_error: Thrown when an arithmetic overflow occurs.
• std::underflow_error: Thrown when an arithmetic underflow occurs.
Example
Example
Example
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