SlideShare une entreprise Scribd logo
1  sur  13
Exception Handling


     Lesson # 16




                   1/15
What is an Exception ?
1 .When a program is executed, unexpected situation may
  occur. Such a situation is called an exception.

EG : a) indexing outside the limits in an array,
    b) giving faulty input data
    c) failure of new to obtain a requested amount of
       memory.



2. An exception is not necessarily the result of a logic
  error in the program. It also can arise from faulty input
  data.
                                          2/15
Example
                                        Index out of range
Division by zero
                                        int array [10];
float x, y;
                                        for (int i=0; i<=10; i++)
….
                                          array [i] = something;
y = 0.0;
float result = x/y
                     No Space
                     class Student
                     {...}
                     int main ()
                     {Student *aStudent;
                     aStudent = new Student (...);
                     ...}

                                                     3/15
To enable the program to take care (handle)of such
exceptional situations, C++ provides the following features:
 1. Try Block
    - The code which might generate a runtime error is
 written within the try block.


2. Throw
   The programmer can generate an exception using throw

3. Catch Block
  Catches the error which may be generated from the code
  within the try block.
 A try block should be followed by one or more catch blocks.



                           General Format - Next Slide
                                              4/15
General Format
Try {
           c++ valid statements;
    }
catch( )
{          error handling part;
 }
catch(argument )
{          error handling part;
 }

                                   5/15
# include <iostream.h>                  We write the code
  int main()                            in a try block
{      int value1, value2, result;
  try
  { cin >> value1;     cin >> value2;          If there is an exception,
                                               we throw it to a handler
    if (value2 == 0)
    { throw ; }                                If there is no exception,
                                               we resume the execution
    result = value1/value2;
    cout <<"result is :"<< result;
  }// end of try

   catch ( )
    { cout << " just cannot divide by zero";
    }// end of catch
                                                     6/15
}// end of main
Some times, we might have many different exceptions


        1. We should write as many catch blocks.
        2. This means also that we should have as many
         throw statements.

        3. BUT(usually), only one try.



 But, which catch block will be instigated? (invoked)



The conflict will be eliminated depending on the parameters
in the throw, i.e., OVERLOADING

                                               7/15
int main()
{ int value1, value2, result;      catch ( )
                                    {cout << " just cannot divide
                                            by zero";
 try                                }// end of catch
 {cin >> value1;cin >> value2;
                                   catch (int v )
   if (value1 < 0)
                                    {cout << v << "is less than zero,
      {throw (value1);
                                                   can’t you see?";
       }
                                    }// end of catch
   if (value2 == 0)
      {throw ;                      …
       }                            return 0;
  result = value1/value2;           }// end of main
  cout <<"result is :"<< result;
 }// end of try
                                                      8/15
Example
Int main ( )                   will this CATCH work ?
{ try{                         Int main ( )
   cout<<“inside try”;         { try{
  throw 100;                      cout<<“inside try”;
  cout<<“will this execute”;     throw 100;
   }                             cout<<“will this
                                  execute”;
                                  }
catch(int I) {
cout <<“the caught an
   exception of value”<<I; }   catch(double I) {
}                              cout <<“the caught an
                                  exception of value”<<I; }
                                              9/15
                               }
Example
Void xtest(int test)
{ cout <<“inside Xtest”<<test;
  if (test) throw test;
}
int main( )
{     try {
         cout<<“inside try”;
         xtest(0);
         xtest(1);
        xtest(2);
         }
catch (int I)
   {cout<<“inside catch”<<I;} }   10/15
EXAMPLE

#include <iostream.h>

void MyFunc( void );

CT 1 class CTest
CT 2 {
CT 3     public:
CT 4        CTest(){};
CT 5        ~CTest(){};
CT 6          const char * ShowReason( ) const
CT 7          { return "Exception in CTest class."; }
CT8 };



                                         11/15
CD 1 class CDtorDemo
CD 2 {      public:
CD 3              CDtorDemo();
CD 4              ~CDtorDemo();
CD 5 };

CD 6 CDtorDemo::CDtorDemo()
CD 7      {cout << "Constructing CDtorDemo." << endl;}
CD 8 CDtorDemo::~CDtorDemo()
CD 9      {cout << "Destructing CDtorDemo." << endl;}

My 1 void MyFunc()
My 2 { CDtorDemo D;
My 3   cout<< "In MyFunc(). Throwing CTest exception."
           << endl;
My 4   throw CTest();
My 5 }                                   12/15
int main()
{
1      cout << "In main." << endl;
2      try
3      { cout << "In try block, calling MyFunc()."<<endl;
4        MyFunc();
5       } // end try
6      catch( CTest E )
7      { cout << "In catch handler." << endl;
8          cout << "Caught CTest exception type: ";
9          cout << E.ShowReason() << endl;
10     } //end catch( CTest E )
11     catch( char *str )
12     {cout << "Caught some other exception: " << str << endl; }
13     cout << "Back in main. Execution resumes here." << endl;
14     return 0;
15 }// end main()
                                                  13/15

Contenu connexe

Tendances

One definition rule - что это такое, и как с этим жить
One definition rule - что это такое, и как с этим житьOne definition rule - что это такое, и как с этим жить
One definition rule - что это такое, и как с этим житьPlatonov Sergey
 
Architecture for Massively Parallel HDL Simulations
Architecture for Massively Parallel HDL Simulations Architecture for Massively Parallel HDL Simulations
Architecture for Massively Parallel HDL Simulations DVClub
 
Потоки в перле изнутри
Потоки в перле изнутриПотоки в перле изнутри
Потоки в перле изнутриIlya Zelenchuk
 
PHP Internals and Virtual Machine
PHP Internals and Virtual MachinePHP Internals and Virtual Machine
PHP Internals and Virtual Machinejulien pauli
 
Digital Voltmeter displaying voltage level on a seven segment display and com...
Digital Voltmeter displaying voltage level on a seven segment display and com...Digital Voltmeter displaying voltage level on a seven segment display and com...
Digital Voltmeter displaying voltage level on a seven segment display and com...Karthik Rathinavel
 
Exception handling
Exception handlingException handling
Exception handlingzindadili
 
4Developers 2018: Evolution of C++ Class Design (Mariusz Łapiński)
4Developers 2018: Evolution of C++ Class Design (Mariusz Łapiński)4Developers 2018: Evolution of C++ Class Design (Mariusz Łapiński)
4Developers 2018: Evolution of C++ Class Design (Mariusz Łapiński)PROIDEA
 
Powerpoint loop examples a
Powerpoint loop examples aPowerpoint loop examples a
Powerpoint loop examples ajaypeebala
 
The Ring programming language version 1.9 book - Part 86 of 210
The Ring programming language version 1.9 book - Part 86 of 210The Ring programming language version 1.9 book - Part 86 of 210
The Ring programming language version 1.9 book - Part 86 of 210Mahmoud Samir Fayed
 
Web Application Development using PHP Chapter 2
Web Application Development using PHP Chapter 2Web Application Development using PHP Chapter 2
Web Application Development using PHP Chapter 2Mohd Harris Ahmad Jaal
 
C Sharp Jn (3)
C Sharp Jn (3)C Sharp Jn (3)
C Sharp Jn (3)jahanullah
 
Block introduce
Block introduceBlock introduce
Block introducebang590
 
PHP Tips for certification - OdW13
PHP Tips for certification - OdW13PHP Tips for certification - OdW13
PHP Tips for certification - OdW13julien pauli
 
Flashback, el primer malware masivo de sistemas Mac
Flashback, el primer malware masivo de sistemas MacFlashback, el primer malware masivo de sistemas Mac
Flashback, el primer malware masivo de sistemas MacESET Latinoamérica
 

Tendances (20)

3
33
3
 
One definition rule - что это такое, и как с этим жить
One definition rule - что это такое, и как с этим житьOne definition rule - что это такое, и как с этим жить
One definition rule - что это такое, и как с этим жить
 
Architecture for Massively Parallel HDL Simulations
Architecture for Massively Parallel HDL Simulations Architecture for Massively Parallel HDL Simulations
Architecture for Massively Parallel HDL Simulations
 
Потоки в перле изнутри
Потоки в перле изнутриПотоки в перле изнутри
Потоки в перле изнутри
 
Clang tidy
Clang tidyClang tidy
Clang tidy
 
MUST CS101 Lab11
MUST CS101 Lab11 MUST CS101 Lab11
MUST CS101 Lab11
 
PHP Internals and Virtual Machine
PHP Internals and Virtual MachinePHP Internals and Virtual Machine
PHP Internals and Virtual Machine
 
Digital Voltmeter displaying voltage level on a seven segment display and com...
Digital Voltmeter displaying voltage level on a seven segment display and com...Digital Voltmeter displaying voltage level on a seven segment display and com...
Digital Voltmeter displaying voltage level on a seven segment display and com...
 
Exception handling
Exception handlingException handling
Exception handling
 
4Developers 2018: Evolution of C++ Class Design (Mariusz Łapiński)
4Developers 2018: Evolution of C++ Class Design (Mariusz Łapiński)4Developers 2018: Evolution of C++ Class Design (Mariusz Łapiński)
4Developers 2018: Evolution of C++ Class Design (Mariusz Łapiński)
 
Powerpoint loop examples a
Powerpoint loop examples aPowerpoint loop examples a
Powerpoint loop examples a
 
The Ring programming language version 1.9 book - Part 86 of 210
The Ring programming language version 1.9 book - Part 86 of 210The Ring programming language version 1.9 book - Part 86 of 210
The Ring programming language version 1.9 book - Part 86 of 210
 
Loops
LoopsLoops
Loops
 
C++17 now
C++17 nowC++17 now
C++17 now
 
Web Application Development using PHP Chapter 2
Web Application Development using PHP Chapter 2Web Application Development using PHP Chapter 2
Web Application Development using PHP Chapter 2
 
C Sharp Jn (3)
C Sharp Jn (3)C Sharp Jn (3)
C Sharp Jn (3)
 
Block introduce
Block introduceBlock introduce
Block introduce
 
PHP Tips for certification - OdW13
PHP Tips for certification - OdW13PHP Tips for certification - OdW13
PHP Tips for certification - OdW13
 
Flashback, el primer malware masivo de sistemas Mac
Flashback, el primer malware masivo de sistemas MacFlashback, el primer malware masivo de sistemas Mac
Flashback, el primer malware masivo de sistemas Mac
 
Percobaan 1
Percobaan 1Percobaan 1
Percobaan 1
 

En vedette (9)

Facebook經營觀察 0820
Facebook經營觀察 0820Facebook經營觀察 0820
Facebook經營觀察 0820
 
Lecture20
Lecture20Lecture20
Lecture20
 
Lecture07
Lecture07Lecture07
Lecture07
 
Lecture21
Lecture21Lecture21
Lecture21
 
Lecture10
Lecture10Lecture10
Lecture10
 
Springwood at music resonate
Springwood at music resonateSpringwood at music resonate
Springwood at music resonate
 
Lecture09
Lecture09Lecture09
Lecture09
 
Lecture17
Lecture17Lecture17
Lecture17
 
Lecture05
Lecture05Lecture05
Lecture05
 

Similaire à Lecture16

exception handling in cpp
exception handling in cppexception handling in cpp
exception handling in cppgourav kottawar
 
Exception handling
Exception handlingException handling
Exception handlingWaqas Abbasi
 
FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2rohassanie
 
WINSEM2016-17_CSE1002_LO_1336_24-JAN-2017_RM003_session 10.pptx
WINSEM2016-17_CSE1002_LO_1336_24-JAN-2017_RM003_session 10.pptxWINSEM2016-17_CSE1002_LO_1336_24-JAN-2017_RM003_session 10.pptx
WINSEM2016-17_CSE1002_LO_1336_24-JAN-2017_RM003_session 10.pptxssusercd11c4
 
CAP444Unit6ExceptionHandling.pptx
CAP444Unit6ExceptionHandling.pptxCAP444Unit6ExceptionHandling.pptx
CAP444Unit6ExceptionHandling.pptxSatyajeetGaur2
 
Final requirement in programming niperos
Final requirement in programming   niperosFinal requirement in programming   niperos
Final requirement in programming niperosmarkings17
 
Final requirement in programming vinson
Final requirement in programming  vinsonFinal requirement in programming  vinson
Final requirement in programming vinsonmonstergeorge
 
Presentation on template and exception
Presentation  on template and exceptionPresentation  on template and exception
Presentation on template and exceptionSajid Alee Mosavi
 
Programming - Marla Fuentes
Programming - Marla FuentesProgramming - Marla Fuentes
Programming - Marla Fuentesmfuentessss
 
Exception handling and templates
Exception handling and templatesException handling and templates
Exception handling and templatesfarhan amjad
 
Aae oop xp_13
Aae oop xp_13Aae oop xp_13
Aae oop xp_13Niit Care
 
Exception Handling
Exception HandlingException Handling
Exception HandlingReddhi Basu
 
Were writing code for a project that dynamically allocates an arra.pdf
Were writing code for a project that dynamically allocates an arra.pdfWere writing code for a project that dynamically allocates an arra.pdf
Were writing code for a project that dynamically allocates an arra.pdffsenterprises
 
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
 
OpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ ProgrammingOpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ ProgrammingOpen Gurukul
 

Similaire à Lecture16 (20)

Exception handling
Exception handlingException handling
Exception handling
 
exception handling in cpp
exception handling in cppexception handling in cpp
exception handling in cpp
 
Exception handling
Exception handlingException handling
Exception handling
 
FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2FP 201 - Unit 3 Part 2
FP 201 - Unit 3 Part 2
 
WINSEM2016-17_CSE1002_LO_1336_24-JAN-2017_RM003_session 10.pptx
WINSEM2016-17_CSE1002_LO_1336_24-JAN-2017_RM003_session 10.pptxWINSEM2016-17_CSE1002_LO_1336_24-JAN-2017_RM003_session 10.pptx
WINSEM2016-17_CSE1002_LO_1336_24-JAN-2017_RM003_session 10.pptx
 
CAP444Unit6ExceptionHandling.pptx
CAP444Unit6ExceptionHandling.pptxCAP444Unit6ExceptionHandling.pptx
CAP444Unit6ExceptionHandling.pptx
 
Exception handling
Exception handlingException handling
Exception handling
 
Final requirement in programming niperos
Final requirement in programming   niperosFinal requirement in programming   niperos
Final requirement in programming niperos
 
Final requirement in programming vinson
Final requirement in programming  vinsonFinal requirement in programming  vinson
Final requirement in programming vinson
 
The Big Three
The Big ThreeThe Big Three
The Big Three
 
Presentation on template and exception
Presentation  on template and exceptionPresentation  on template and exception
Presentation on template and exception
 
Pre zen ta sion
Pre zen ta sionPre zen ta sion
Pre zen ta sion
 
Programming - Marla Fuentes
Programming - Marla FuentesProgramming - Marla Fuentes
Programming - Marla Fuentes
 
Exception handling and templates
Exception handling and templatesException handling and templates
Exception handling and templates
 
Catch and throw blocks
Catch and throw blocksCatch and throw blocks
Catch and throw blocks
 
Aae oop xp_13
Aae oop xp_13Aae oop xp_13
Aae oop xp_13
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Were writing code for a project that dynamically allocates an arra.pdf
Were writing code for a project that dynamically allocates an arra.pdfWere writing code for a project that dynamically allocates an arra.pdf
Were writing code for a project that dynamically allocates an arra.pdf
 
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
 
OpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ ProgrammingOpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ Programming
 

Plus de elearning_portal (6)

Lecture19
Lecture19Lecture19
Lecture19
 
Lecture18
Lecture18Lecture18
Lecture18
 
Lecture06
Lecture06Lecture06
Lecture06
 
Lecture03
Lecture03Lecture03
Lecture03
 
Lecture02
Lecture02Lecture02
Lecture02
 
Lecture01
Lecture01Lecture01
Lecture01
 

Dernier

2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Association for Project Management
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jisc
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...Nguyen Thanh Tu Collection
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxJisc
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentationcamerronhm
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...pradhanghanshyam7136
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - Englishneillewis46
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxPooja Bhuva
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfNirmal Dwivedi
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 

Dernier (20)

2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 

Lecture16

  • 1. Exception Handling Lesson # 16 1/15
  • 2. What is an Exception ? 1 .When a program is executed, unexpected situation may occur. Such a situation is called an exception. EG : a) indexing outside the limits in an array, b) giving faulty input data c) failure of new to obtain a requested amount of memory. 2. An exception is not necessarily the result of a logic error in the program. It also can arise from faulty input data. 2/15
  • 3. Example Index out of range Division by zero int array [10]; float x, y; for (int i=0; i<=10; i++) …. array [i] = something; y = 0.0; float result = x/y No Space class Student {...} int main () {Student *aStudent; aStudent = new Student (...); ...} 3/15
  • 4. To enable the program to take care (handle)of such exceptional situations, C++ provides the following features: 1. Try Block - The code which might generate a runtime error is written within the try block. 2. Throw The programmer can generate an exception using throw 3. Catch Block Catches the error which may be generated from the code within the try block. A try block should be followed by one or more catch blocks. General Format - Next Slide 4/15
  • 5. General Format Try { c++ valid statements; } catch( ) { error handling part; } catch(argument ) { error handling part; } 5/15
  • 6. # include <iostream.h> We write the code int main() in a try block { int value1, value2, result; try { cin >> value1; cin >> value2; If there is an exception, we throw it to a handler if (value2 == 0) { throw ; } If there is no exception, we resume the execution result = value1/value2; cout <<"result is :"<< result; }// end of try catch ( ) { cout << " just cannot divide by zero"; }// end of catch 6/15 }// end of main
  • 7. Some times, we might have many different exceptions 1. We should write as many catch blocks. 2. This means also that we should have as many throw statements. 3. BUT(usually), only one try. But, which catch block will be instigated? (invoked) The conflict will be eliminated depending on the parameters in the throw, i.e., OVERLOADING 7/15
  • 8. int main() { int value1, value2, result; catch ( ) {cout << " just cannot divide by zero"; try }// end of catch {cin >> value1;cin >> value2; catch (int v ) if (value1 < 0) {cout << v << "is less than zero, {throw (value1); can’t you see?"; } }// end of catch if (value2 == 0) {throw ; … } return 0; result = value1/value2; }// end of main cout <<"result is :"<< result; }// end of try 8/15
  • 9. Example Int main ( ) will this CATCH work ? { try{ Int main ( ) cout<<“inside try”; { try{ throw 100; cout<<“inside try”; cout<<“will this execute”; throw 100; } cout<<“will this execute”; } catch(int I) { cout <<“the caught an exception of value”<<I; } catch(double I) { } cout <<“the caught an exception of value”<<I; } 9/15 }
  • 10. Example Void xtest(int test) { cout <<“inside Xtest”<<test; if (test) throw test; } int main( ) { try { cout<<“inside try”; xtest(0); xtest(1); xtest(2); } catch (int I) {cout<<“inside catch”<<I;} } 10/15
  • 11. EXAMPLE #include <iostream.h> void MyFunc( void ); CT 1 class CTest CT 2 { CT 3 public: CT 4 CTest(){}; CT 5 ~CTest(){}; CT 6 const char * ShowReason( ) const CT 7 { return "Exception in CTest class."; } CT8 }; 11/15
  • 12. CD 1 class CDtorDemo CD 2 { public: CD 3 CDtorDemo(); CD 4 ~CDtorDemo(); CD 5 }; CD 6 CDtorDemo::CDtorDemo() CD 7 {cout << "Constructing CDtorDemo." << endl;} CD 8 CDtorDemo::~CDtorDemo() CD 9 {cout << "Destructing CDtorDemo." << endl;} My 1 void MyFunc() My 2 { CDtorDemo D; My 3 cout<< "In MyFunc(). Throwing CTest exception." << endl; My 4 throw CTest(); My 5 } 12/15
  • 13. int main() { 1 cout << "In main." << endl; 2 try 3 { cout << "In try block, calling MyFunc()."<<endl; 4 MyFunc(); 5 } // end try 6 catch( CTest E ) 7 { cout << "In catch handler." << endl; 8 cout << "Caught CTest exception type: "; 9 cout << E.ShowReason() << endl; 10 } //end catch( CTest E ) 11 catch( char *str ) 12 {cout << "Caught some other exception: " << str << endl; } 13 cout << "Back in main. Execution resumes here." << endl; 14 return 0; 15 }// end main() 13/15