SlideShare uma empresa 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

Mais conteúdo relacionado

Mais procurados

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
 

Mais procurados (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
 

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

Semelhante 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
 

Semelhante 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
 

Mais de elearning_portal (6)

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

Último

1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 

Último (20)

1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 

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