SlideShare ist ein Scribd-Unternehmen logo
1 von 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

Weitere ähnliche Inhalte

Was ist angesagt?

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
 

Was ist angesagt? (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
 

Andere mochten auch (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
 

Ähnlich wie 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
 

Ähnlich wie 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
 

Mehr von elearning_portal (6)

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

Kürzlich hochgeladen

General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 
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
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfSherif Taha
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024Elizabeth Walsh
 
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
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxCeline George
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxPooja Bhuva
 
Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxUmeshTimilsina1
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxJisc
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfDr Vijay Vishwakarma
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the ClassroomPooky Knightsmith
 
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
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxPooja Bhuva
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxPooja Bhuva
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Pooja Bhuva
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 
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
 

Kürzlich hochgeladen (20)

General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
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
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
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Ữ Â...
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 
Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptx
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
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
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
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
 

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