SlideShare a Scribd company logo
1 of 17
Subject : Object Oriented Programming with C++
Topic : Exception Handling
Contents
Introduction to Exception
Try – Catch – Throw
Multiple Catch
Catch All
Rethrowing Exception
What is exception?
An exception is an unexpected event that occurs
during runtime and causes normal program flow to
be disrupted.
Some Examples are:
– Divide by zero errors
– Accessing the elements of an array beyond limit.
– Invalid Input etc.
How do we Handle
Exception?
There are different types of mechanism
used to handle the exception and some
of them are as follow:
• Try-Catch-Throw.
• Multiple Catch.
• Catch All.
• Rethrowing Exception.
• Implementing Exception.
Try-Catch-Throw
Try key word is used to preface a block
of statements which may generate
exceptions.
This block is known as Try block.
When an exception is detected, it is
thrown using the Throw statement in the
try block.
The Catch block catches the exception
thrown by the try block.
The catch block must be immediately
follow the try block that throws the
Detects and throws an
exception
try block
Catches and handles the
exception
catch block
Exception
object
Figure : The block throwing exception
Syntax:
……
……
try
{
……
throw exception; // or throw (exception);
……
}
Catch(type arg)
{
……
……
}
Example:
Try Block Throwing an Exception
#include<iostream.h>
#include<conio.h>
int main()
{
int a,b;
cout<<“enter values of a and b:”;
cin>>a>>b;
int x = a-b;
try
{
if(x != 0) { cout<<“n result(a/x)=“<<a/x<<“n”; }
else { throw(x); // throws integer object }
}catch(int i){ cout<<“exception caught”; }
return 0;
}
Multiple Catch
It is possible that a program segment
has more than one condition to throw an
exception.
In such cases we can associate more
than one Catch statement with a single
try block.
When an exception is thrown , the
exception handlers are searched in order
for an appropriate match.
It is possible that argument of several
catch statements match the type of an
exception.
In such cases, the first handler that
matches the exception type is executed.
Syntax:
try
{
//try block
}
catch(type 1 arg)
{
//catch block 1
}
catch(type 2 arg)
{
//catch block 2
}
……
catch(type N arg)
{
// catch blockN
}
Example:
Multiple Catch Statements
#include<iostream.h>
#include<conio.h>
void test(int x)
{
try
{
if(x == 1) throw x;
else if(x==0) throw ‘x’;
else if( x== -1) throw 1.0;
}
catch(char c) { cout<<“caught a character”; }
catch(int m) { cout<<“caught an integer;” }
catch(double b) { cout<<“caught a double;” }
}
int main()
{
test(1);
test(0);
test(-1);
return 0; }
Catch All
In some situations, we may not be able to
anticipate all possible types of exceptions and
therefore may not be able to design independent
catch handler to catch them.
In such circumstances, we can force a catch
statement to catch all the exceptions instead of
certain type alone.
Syntax:
catch(…)
{
//statements for processing
//all exceptions
}
Example:
Catching All Statements
#include<iostream.h>
#include<conio.h>
void test(int x)
{
try
{
if(x == 1) throw x;
else if(x==0) throw ‘x’;
else if( x== -1) throw 1.0;
}
catch(…) { cout<<“caught an exception”; }
}
int main()
{
Cout<<“testing generic catch”;
test(1);
test(0);
test(-1);
return 0; }
Rethrowing Exception
A handler may decide to rethrow the
exception caught without processing it.
In such situation, we may simply invoke
throw without any argument as shown
below:
throw;
This causes the current exception to be
thrown to the next enclosing try/catch
sequence and is caught by a catch
statement listed after that enclosing try
block
Example:
Re-throw an Exception
#include<iostream.h>
#include<conio.h>
void sub(int i,int j)
{
cout<<“inside function sub()”;
try
{
if(j==0) { throw j; }
else { cout<<“subtraction=“<<i-j<<“n”; }
}catch(int)
{
cout<<“caught null value”;
throw;
}
cout<<“end of sub()”;
}
int main()
{
cout<<“n inside function main”;
try{
sub(8,5);
sub(0,5);
}
catch(int){
cout<<“caught null inside main”;
}
cout<<“end of main()”;
return 0;
}
THANK YOU

More Related Content

What's hot

Exception Handling in C++
Exception Handling in C++Exception Handling in C++
Exception Handling in C++Deepak Tathe
 
Exception Handling in the C++ Constructor
Exception Handling in the C++ ConstructorException Handling in the C++ Constructor
Exception Handling in the C++ ConstructorSomenath Mukhopadhyay
 
Exception handling
Exception handlingException handling
Exception handlingpooja kumari
 
Exception Handling
Exception HandlingException Handling
Exception Handlingbackdoor
 
Exception handling and templates
Exception handling and templatesException handling and templates
Exception handling and templatesfarhan amjad
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVASURIT DATTA
 
Java Pitfalls and Good-to-Knows
Java Pitfalls and Good-to-KnowsJava Pitfalls and Good-to-Knows
Java Pitfalls and Good-to-KnowsMiquel Martin
 
Error handling: error code vs. exception
Error handling: error code vs. exceptionError handling: error code vs. exception
Error handling: error code vs. exceptionChieh (Jack) Yu
 
Understanding Exception Handling in .Net
Understanding Exception Handling in .NetUnderstanding Exception Handling in .Net
Understanding Exception Handling in .NetMindfire Solutions
 
Programming Basics if then else, switch, operators
Programming Basics if then else, switch, operatorsProgramming Basics if then else, switch, operators
Programming Basics if then else, switch, operatorsTrivuz ত্রিভুজ
 
Intro to JavaScript - Week 3: Control Statements
Intro to JavaScript - Week 3: Control StatementsIntro to JavaScript - Week 3: Control Statements
Intro to JavaScript - Week 3: Control StatementsJeongbae Oh
 
Exception Handling
Exception HandlingException Handling
Exception HandlingAlpesh Oza
 

What's hot (20)

Exception Handling in C++
Exception Handling in C++Exception Handling in C++
Exception Handling in C++
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception Handling in the C++ Constructor
Exception Handling in the C++ ConstructorException Handling in the C++ Constructor
Exception Handling in the C++ Constructor
 
What is Exception Handling?
What is Exception Handling?What is Exception Handling?
What is Exception Handling?
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Exception handling and templates
Exception handling and templatesException handling and templates
Exception handling and templates
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
 
Java Pitfalls and Good-to-Knows
Java Pitfalls and Good-to-KnowsJava Pitfalls and Good-to-Knows
Java Pitfalls and Good-to-Knows
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
exception handling
 exception handling exception handling
exception handling
 
43c
43c43c
43c
 
Error handling: error code vs. exception
Error handling: error code vs. exceptionError handling: error code vs. exception
Error handling: error code vs. exception
 
Exception handling
Exception handlingException handling
Exception handling
 
Understanding Exception Handling in .Net
Understanding Exception Handling in .NetUnderstanding Exception Handling in .Net
Understanding Exception Handling in .Net
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Programming Basics if then else, switch, operators
Programming Basics if then else, switch, operatorsProgramming Basics if then else, switch, operators
Programming Basics if then else, switch, operators
 
Intro to JavaScript - Week 3: Control Statements
Intro to JavaScript - Week 3: Control StatementsIntro to JavaScript - Week 3: Control Statements
Intro to JavaScript - Week 3: Control Statements
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Presentation1
Presentation1Presentation1
Presentation1
 

Similar to Exception Handling in C

Exception Handling
Exception HandlingException Handling
Exception HandlingPRN USM
 
L12.2 Exception handling.pdf
L12.2  Exception handling.pdfL12.2  Exception handling.pdf
L12.2 Exception handling.pdfMaddalaSeshu
 
Exceptions and Exception Handling in C++
Exceptions and Exception Handling in C++Exceptions and Exception Handling in C++
Exceptions and Exception Handling in C++IRJET Journal
 
CAP444Unit6ExceptionHandling.pptx
CAP444Unit6ExceptionHandling.pptxCAP444Unit6ExceptionHandling.pptx
CAP444Unit6ExceptionHandling.pptxSatyajeetGaur2
 
Exceptions in C++ Object Oriented Programming.pptx
Exceptions in C++ Object Oriented Programming.pptxExceptions in C++ Object Oriented Programming.pptx
Exceptions in C++ Object Oriented Programming.pptxestorebackupr
 
17 exception handling - ii
17 exception handling - ii17 exception handling - ii
17 exception handling - iiRavindra Rathore
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javapriyankazope
 
Unit 4 exceptions and threads
Unit 4 exceptions and threadsUnit 4 exceptions and threads
Unit 4 exceptions and threadsDevaKumari Vijay
 
Rethrowing exception- JAVA
Rethrowing exception- JAVARethrowing exception- JAVA
Rethrowing exception- JAVARajan Shah
 
Exception Handling
Exception HandlingException Handling
Exception HandlingReddhi Basu
 
Exception handling
Exception handlingException handling
Exception handlingIblesoft
 
EXCEPTION HANDLING in C++
EXCEPTION HANDLING in C++EXCEPTION HANDLING in C++
EXCEPTION HANDLING in C++Prof Ansari
 
Unit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application developmentUnit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application developmentrohitgudasi18
 
Web technology
Web technology Web technology
Web technology Siva Priya
 

Similar to Exception Handling in C (20)

Exception Handling
Exception HandlingException Handling
Exception Handling
 
L12.2 Exception handling.pdf
L12.2  Exception handling.pdfL12.2  Exception handling.pdf
L12.2 Exception handling.pdf
 
Exceptions and Exception Handling in C++
Exceptions and Exception Handling in C++Exceptions and Exception Handling in C++
Exceptions and Exception Handling in C++
 
CAP444Unit6ExceptionHandling.pptx
CAP444Unit6ExceptionHandling.pptxCAP444Unit6ExceptionHandling.pptx
CAP444Unit6ExceptionHandling.pptx
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 
Exceptions in C++ Object Oriented Programming.pptx
Exceptions in C++ Object Oriented Programming.pptxExceptions in C++ Object Oriented Programming.pptx
Exceptions in C++ Object Oriented Programming.pptx
 
17 exception handling - ii
17 exception handling - ii17 exception handling - ii
17 exception handling - ii
 
Lecture 9.pdf
Lecture 9.pdfLecture 9.pdf
Lecture 9.pdf
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Unit 4 exceptions and threads
Unit 4 exceptions and threadsUnit 4 exceptions and threads
Unit 4 exceptions and threads
 
Rethrowing exception- JAVA
Rethrowing exception- JAVARethrowing exception- JAVA
Rethrowing exception- JAVA
 
Exceptions in java
Exceptions in javaExceptions in java
Exceptions in java
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Exception handling
Exception handlingException handling
Exception handling
 
EXCEPTION HANDLING in C++
EXCEPTION HANDLING in C++EXCEPTION HANDLING in C++
EXCEPTION HANDLING in C++
 
Unit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application developmentUnit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application development
 
java.pptx
java.pptxjava.pptx
java.pptx
 
Java unit3
Java unit3Java unit3
Java unit3
 
exception handling
exception handlingexception handling
exception handling
 
Web technology
Web technology Web technology
Web technology
 

More from zindadili

Exception handling
Exception handlingException handling
Exception handlingzindadili
 
Virtual function
Virtual functionVirtual function
Virtual functionzindadili
 
Operator overloaing
Operator overloaingOperator overloaing
Operator overloaingzindadili
 
Operator overloading2
Operator overloading2Operator overloading2
Operator overloading2zindadili
 
Polymorphism
PolymorphismPolymorphism
Polymorphismzindadili
 
Function overloading
Function overloadingFunction overloading
Function overloadingzindadili
 
Hierarchical inheritance
Hierarchical inheritanceHierarchical inheritance
Hierarchical inheritancezindadili
 
Hybrid inheritance
Hybrid inheritanceHybrid inheritance
Hybrid inheritancezindadili
 
Multiple inheritance
Multiple inheritanceMultiple inheritance
Multiple inheritancezindadili
 
Abstraction1
Abstraction1Abstraction1
Abstraction1zindadili
 
Access specifier
Access specifierAccess specifier
Access specifierzindadili
 
Friend function
Friend functionFriend function
Friend functionzindadili
 

More from zindadili (20)

Namespaces
NamespacesNamespaces
Namespaces
 
Namespace1
Namespace1Namespace1
Namespace1
 
Exception handling
Exception handlingException handling
Exception handling
 
Templates2
Templates2Templates2
Templates2
 
Templates1
Templates1Templates1
Templates1
 
Virtual function
Virtual functionVirtual function
Virtual function
 
Operator overloaing
Operator overloaingOperator overloaing
Operator overloaing
 
Operator overloading2
Operator overloading2Operator overloading2
Operator overloading2
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Function overloading
Function overloadingFunction overloading
Function overloading
 
Aggregation
AggregationAggregation
Aggregation
 
Hierarchical inheritance
Hierarchical inheritanceHierarchical inheritance
Hierarchical inheritance
 
Hybrid inheritance
Hybrid inheritanceHybrid inheritance
Hybrid inheritance
 
Multiple inheritance
Multiple inheritanceMultiple inheritance
Multiple inheritance
 
Abstraction1
Abstraction1Abstraction1
Abstraction1
 
Abstraction
AbstractionAbstraction
Abstraction
 
Access specifier
Access specifierAccess specifier
Access specifier
 
Inheritance
InheritanceInheritance
Inheritance
 
Friend function
Friend functionFriend function
Friend function
 
Enum
EnumEnum
Enum
 

Recently uploaded

Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptxSherlyMaeNeri
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........LeaCamillePacle
 

Recently uploaded (20)

Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptx
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 
Rapple "Scholarly Communications and the Sustainable Development Goals"
Rapple "Scholarly Communications and the Sustainable Development Goals"Rapple "Scholarly Communications and the Sustainable Development Goals"
Rapple "Scholarly Communications and the Sustainable Development Goals"
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........
 

Exception Handling in C

  • 1. Subject : Object Oriented Programming with C++ Topic : Exception Handling
  • 2. Contents Introduction to Exception Try – Catch – Throw Multiple Catch Catch All Rethrowing Exception
  • 3. What is exception? An exception is an unexpected event that occurs during runtime and causes normal program flow to be disrupted. Some Examples are: – Divide by zero errors – Accessing the elements of an array beyond limit. – Invalid Input etc.
  • 4. How do we Handle Exception? There are different types of mechanism used to handle the exception and some of them are as follow: • Try-Catch-Throw. • Multiple Catch. • Catch All. • Rethrowing Exception. • Implementing Exception.
  • 5. Try-Catch-Throw Try key word is used to preface a block of statements which may generate exceptions. This block is known as Try block. When an exception is detected, it is thrown using the Throw statement in the try block. The Catch block catches the exception thrown by the try block. The catch block must be immediately follow the try block that throws the
  • 6. Detects and throws an exception try block Catches and handles the exception catch block Exception object Figure : The block throwing exception
  • 7. Syntax: …… …… try { …… throw exception; // or throw (exception); …… } Catch(type arg) { …… …… }
  • 8. Example: Try Block Throwing an Exception #include<iostream.h> #include<conio.h> int main() { int a,b; cout<<“enter values of a and b:”; cin>>a>>b; int x = a-b; try { if(x != 0) { cout<<“n result(a/x)=“<<a/x<<“n”; } else { throw(x); // throws integer object } }catch(int i){ cout<<“exception caught”; } return 0; }
  • 9. Multiple Catch It is possible that a program segment has more than one condition to throw an exception. In such cases we can associate more than one Catch statement with a single try block. When an exception is thrown , the exception handlers are searched in order for an appropriate match. It is possible that argument of several catch statements match the type of an exception. In such cases, the first handler that matches the exception type is executed.
  • 10. Syntax: try { //try block } catch(type 1 arg) { //catch block 1 } catch(type 2 arg) { //catch block 2 } …… catch(type N arg) { // catch blockN }
  • 11. Example: Multiple Catch Statements #include<iostream.h> #include<conio.h> void test(int x) { try { if(x == 1) throw x; else if(x==0) throw ‘x’; else if( x== -1) throw 1.0; } catch(char c) { cout<<“caught a character”; } catch(int m) { cout<<“caught an integer;” } catch(double b) { cout<<“caught a double;” } } int main() { test(1); test(0); test(-1); return 0; }
  • 12. Catch All In some situations, we may not be able to anticipate all possible types of exceptions and therefore may not be able to design independent catch handler to catch them. In such circumstances, we can force a catch statement to catch all the exceptions instead of certain type alone. Syntax: catch(…) { //statements for processing //all exceptions }
  • 13. Example: Catching All Statements #include<iostream.h> #include<conio.h> void test(int x) { try { if(x == 1) throw x; else if(x==0) throw ‘x’; else if( x== -1) throw 1.0; } catch(…) { cout<<“caught an exception”; } } int main() { Cout<<“testing generic catch”; test(1); test(0); test(-1); return 0; }
  • 14. Rethrowing Exception A handler may decide to rethrow the exception caught without processing it. In such situation, we may simply invoke throw without any argument as shown below: throw; This causes the current exception to be thrown to the next enclosing try/catch sequence and is caught by a catch statement listed after that enclosing try block
  • 15. Example: Re-throw an Exception #include<iostream.h> #include<conio.h> void sub(int i,int j) { cout<<“inside function sub()”; try { if(j==0) { throw j; } else { cout<<“subtraction=“<<i-j<<“n”; } }catch(int) { cout<<“caught null value”; throw; } cout<<“end of sub()”; }
  • 16. int main() { cout<<“n inside function main”; try{ sub(8,5); sub(0,5); } catch(int){ cout<<“caught null inside main”; } cout<<“end of main()”; return 0; }