SlideShare una empresa de Scribd logo
1 de 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

Más contenido relacionado

La actualidad más candente

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
 

La actualidad más candente (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
 

Destacado (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
 

Similar a 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
 

Similar a 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
 

Más de elearning_portal (6)

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

Último

Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management SystemChristalin Nelson
 
Presentation Activity 2. Unit 3 transv.pptx
Presentation Activity 2. Unit 3 transv.pptxPresentation Activity 2. Unit 3 transv.pptx
Presentation Activity 2. Unit 3 transv.pptxRosabel UA
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Seán Kennedy
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
The Contemporary World: The Globalization of World Politics
The Contemporary World: The Globalization of World PoliticsThe Contemporary World: The Globalization of World Politics
The Contemporary World: The Globalization of World PoliticsRommel Regala
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operationalssuser3e220a
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
Activity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationActivity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationRosabel UA
 
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
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmStan Meyer
 
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
 
TEACHER REFLECTION FORM (NEW SET........).docx
TEACHER REFLECTION FORM (NEW SET........).docxTEACHER REFLECTION FORM (NEW SET........).docx
TEACHER REFLECTION FORM (NEW SET........).docxruthvilladarez
 

Último (20)

Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management System
 
Presentation Activity 2. Unit 3 transv.pptx
Presentation Activity 2. Unit 3 transv.pptxPresentation Activity 2. Unit 3 transv.pptx
Presentation Activity 2. Unit 3 transv.pptx
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
The Contemporary World: The Globalization of World Politics
The Contemporary World: The Globalization of World PoliticsThe Contemporary World: The Globalization of World Politics
The Contemporary World: The Globalization of World Politics
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operational
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
Activity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationActivity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translation
 
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
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and Film
 
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)
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
TEACHER REFLECTION FORM (NEW SET........).docx
TEACHER REFLECTION FORM (NEW SET........).docxTEACHER REFLECTION FORM (NEW SET........).docx
TEACHER REFLECTION FORM (NEW SET........).docx
 

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