SlideShare una empresa de Scribd logo
1 de 2
Descargar para leer sin conexión
Object Oriented Programming                                                                           Object Oriented Programming

                                         EXCEPTIONS
 Exceptions provide a systematic, object-oriented approach to handle runtime errors                      The problem with this approach is that every single call to such a function
 generated by C++ classes.
                                                                                                         must be examined by the program.
 To qualify as an exception, such errors must occur as a result of some action taken
 within a program and they must be the ones the program itself can discover.                            Surrounding each function call with an if...else statement and inserting
 For example, a constructor in a user-written string class might generate an exception                  statements to handle the error (or to call an error-handler routine) makes the
 if the application tries to initialize an object with a string that’s too long.                        listing long and hard to read.
 Similarly, a program can check if a file was opened or written successfully and                        Also, it’s not practical for some functions to return an error value. For example,
 generate an exception if it was not.                                                                   imagine a min() function that returns the minimum of two values. All possible
 Let’s look at how the process was handled in the past.                                                 return values from this function represent valid outcomes. There’s no value left
In C language programs, an error                                                                        to use as an error return.
                                         if( somefunc() == ERROR RETURN VALUE )
                                                             ERROR_RETURN_VALUE
is ft
i often signaled b returning a
           i   l d by t      i
                                                 // handle the error or call error-handler function     The problem becomes more complex when classes are used because errors may
particular value from the function
                                         else                                                           take place without a function being explicitly called. For example, suppose an
in which it occurred.
                                                 // proceed normally                                    application defines objects of a class:
For example, many math functions if( anotherfunc() == NULL )
return a special value to indicate               // handle the error or call error-handler function                 SomeClass obj1, obj2, obj3;
an error, and disk file functions        else
often return NULL or 0 to signal
                                                                                                        How will the application find out if an error occurred in the class constructor?
                                                 // proceed normally
an error.                                if( thirdfunc() == 0 )                                         The constructor is called implicitly, so there’s no return value to be checked.
Each time you call one of these                  // handle the error or call error-handler function
functions, you check the return          else // proceed normally
value.

   www.buzluca.info/oop                                       ©1999-2008 Dr. Feza BUZLUCA   10.1         www.buzluca.info/oop                                  ©1999-2008 Dr. Feza BUZLUCA   10.2




Object Oriented Programming                                                                           Object Oriented Programming

              Exception Syntax                                                                         Example; a fraction function: It takes the numerator and denominator as
                                                                                                       parameters, calculates the result of the fraction and returns it back.
If an error is detected in a member function, this member function informs the                         If the denominator is zero an exception must be thrown.
application that an error has occurred. When exceptions are used, this is called                              float fraction(int num, int denom)
throwing an exception.                                                                                        {
In the application, a separate section of code is installed to handle the error. This                              if(denom==0) throw "Divide by zero";
code is called an exception handler or catch block: it catches the exceptions                                      return static_cast<float>(num) / denom;
thrown by the member function.                                                                                }
Any code in the application that uses objects of the class is enclosed in a try block.                        int main()
                                                                                                              {
The exception mechanism uses three new C++ keywords: throw, catch, and try.
                                                                                                                   int numerator, denominator;
      Throwing an exception:                                                                                       cout << endl << "Enter the numerator ";;
                                                                                                                   cin >> numerator;
      Syntax of a function f that throws an exception:
                                                                                                                   cout << endl << "Enter the denominator ";
         return_type f( parameters ) {                                                                             cin >> denominator;
             if ( exception_condition ) throw exceptioncode;                                                       try{
                                                                                                                       cout << fraction(numerator, denominator);
                  // normal operation
                                                                                                                   }
             return expression;                                                                                    catch (const char * result){             The catch block must immediately
          }                                                                                                             cout << endl << result;             follow the try block.
      Here exceptioncode can be any variable or constant of any built-in type (as                                 }
                                                                                                                 cout << endl << "End of Program";
      char, int, char *) or it can also be an object that defines the exception.                                 return 0;                                         See Example: e10_1.cpp
                                                                                                              }
   www.buzluca.info/oop                                       ©1999-2008 Dr. Feza BUZLUCA   10.3         www.buzluca.info/oop                                  ©1999-2008 Dr. Feza BUZLUCA   10.4




Object Oriented Programming                                                                           Object Oriented Programming

  In a catch block you may catch only the type of the exception-code, if the code                             If a function throws exceptions of different types, then a separate catch
  itself is not necessary.                                                                                    block must be written for each exception type.
     catch (const char *){
             cout << endl << "ERROR";          // The thrown data is unknown                          try {
     }                                                                                                     cout << fraction(numerator , denominator);
                                                                                                      }
    A function may throw more then one exceptions. For example if we don't                            catch (const char * result) {               // Catch block for exceptions of type char *
    want negative denominators, we can write the fraction function as follows:                              cout << endl << result;
     float fraction(int num, int denom)                                                               }
     {                                                                                                catch (int) {            // Catch block for exceptions of type int (value is not taken)
         if(denom == 0) throw "Divide by zero";                                                             cout << endl << "ERROR";
         if(denom < 0) throw "Negative denominator";                                                  }                                                  See Example: e10_2.cpp
         return static_cast<float>(num) / denom;
     }
    A function may also throw exceptions of different types.
                                                                                                        Like built-in data types, objects can also be thrown and caught as exceptions.
     float fraction(int num, int denom)
                                                                                                        Examine the example e10_3.cpp. In this program we have a class: Stack. This
     {
                                                                                                        class includes two functions push and pop. If an error occurs, these functions
         if(denom == 0) throw "Divide by zero";                 // throws char *
                                                                                                        throw an object of class Error.
         if(denom < 0) throw "Negative denominator";            // throws char *
         if(denom > 1000) throw -1;                             // throws int                                                                             See Example: e10_3.cpp
         return static_cast<float>(num) / denom;
     }
   www.buzluca.info/oop                                       ©1999-2008 Dr. Feza BUZLUCA   10.5         www.buzluca.info/oop                                  ©1999-2008 Dr. Feza BUZLUCA   10.6




                                                                                                                                                                                                    1
Object Oriented Programming                                                                     Object Oriented Programming

                                                                                                     int main()
   Exceptions are necessary to find out if an error occurred in the class                            {
   constructor. Constructors are called implicitly and there’s no return value to be                      char input[20];                            // To take strings from keyboard
   checked.                                                                                               String *str;                               // Pointer to objects
   Example: The creator of the String class does not allow the contents of the                            bool again;                                 // loop condition
   String to be longer than 10 characters.                                                                do{
           class String{                                                                                       again = false;
                enum { MAX_SIZE = 10 };         // MAX_SIZE is a constant                                      cout << " Enter a string: ";
                int size;                                                                                      cin >> input;
                char *contents;                                                                                try{
            public:                                                                                               str= new String(input);            // calls the constructor
                String(const char *);          // Constructor                                                  }
                void print() const;            // A member function                                            catch (const char *){
                ~String();                     // Destructor                                                       cout << "String is too long" << endl;
           };                                                                                                      again = true;
           String::String(const char *in_data)                                                                 }
           {                                                                                              }while(again);
                cout<< "Constructor has been invoked" << endl;                                            str->print();                          // The creation of the object is guaranteed
                size = strlen(in_data);                                                                   delete str;
                if (size > MAX_SIZE) throw "String too long";                                             return 0;
                contents = new char[size +1];        // +1 for null character                        }
                strcpy(contents, in_data);                                                      The only way to exit the do-while loop is giving strings shorter than 10
            }                                                                                   characters. Otherwise the object is not created.              See Example: e10_4.cpp
   www.buzluca.info/oop                                    ©1999-2008 Dr. Feza BUZLUCA   10.7      www.buzluca.info/oop                                    ©1999-2008 Dr. Feza BUZLUCA   10.8




                                                                                                                                                                                                2

Más contenido relacionado

La actualidad más candente

Latest C Interview Questions and Answers
Latest C Interview Questions and AnswersLatest C Interview Questions and Answers
Latest C Interview Questions and AnswersDaisyWatson5
 
C++ programming with jni
C++ programming with jniC++ programming with jni
C++ programming with jniPeter Hagemeyer
 
Dart function - Recursive functions
Dart function - Recursive functionsDart function - Recursive functions
Dart function - Recursive functionsKoAungThuOo1
 
Java 7 new features
Java 7 new featuresJava 7 new features
Java 7 new featuresShivam Goel
 
FP 201 - Unit 6
FP 201 - Unit 6FP 201 - Unit 6
FP 201 - Unit 6rohassanie
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming iiPrashant Kalkar
 
5. using variables, data, expressions and constants
5. using variables, data, expressions and constants5. using variables, data, expressions and constants
5. using variables, data, expressions and constantsCtOlaf
 
Tesseract. Recognizing Errors in Recognition Software
Tesseract. Recognizing Errors in Recognition SoftwareTesseract. Recognizing Errors in Recognition Software
Tesseract. Recognizing Errors in Recognition SoftwareAndrey Karpov
 
Checking WinMerge with PVS-Studio for the second time
Checking WinMerge with PVS-Studio for the second timeChecking WinMerge with PVS-Studio for the second time
Checking WinMerge with PVS-Studio for the second timePVS-Studio
 
Memory management in C++
Memory management in C++Memory management in C++
Memory management in C++Ilio Catallo
 
Web application architecture
Web application architectureWeb application architecture
Web application architectureIlio Catallo
 
20 cool features that is in PHP 7, we missed in PHP 5. Let walkthrough with t...
20 cool features that is in PHP 7, we missed in PHP 5. Let walkthrough with t...20 cool features that is in PHP 7, we missed in PHP 5. Let walkthrough with t...
20 cool features that is in PHP 7, we missed in PHP 5. Let walkthrough with t...DrupalMumbai
 
Effective Java - Enum and Annotations
Effective Java - Enum and AnnotationsEffective Java - Enum and Annotations
Effective Java - Enum and AnnotationsRoshan Deniyage
 
C questions
C questionsC questions
C questionsparm112
 

La actualidad más candente (20)

Latest C Interview Questions and Answers
Latest C Interview Questions and AnswersLatest C Interview Questions and Answers
Latest C Interview Questions and Answers
 
C++ programming with jni
C++ programming with jniC++ programming with jni
C++ programming with jni
 
Dart function - Recursive functions
Dart function - Recursive functionsDart function - Recursive functions
Dart function - Recursive functions
 
Functional programming
Functional programmingFunctional programming
Functional programming
 
Pl sql programme
Pl sql programmePl sql programme
Pl sql programme
 
85ec7 session2 c++
85ec7 session2 c++85ec7 session2 c++
85ec7 session2 c++
 
Java 7 new features
Java 7 new featuresJava 7 new features
Java 7 new features
 
FP 201 - Unit 6
FP 201 - Unit 6FP 201 - Unit 6
FP 201 - Unit 6
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
 
5. using variables, data, expressions and constants
5. using variables, data, expressions and constants5. using variables, data, expressions and constants
5. using variables, data, expressions and constants
 
Tesseract. Recognizing Errors in Recognition Software
Tesseract. Recognizing Errors in Recognition SoftwareTesseract. Recognizing Errors in Recognition Software
Tesseract. Recognizing Errors in Recognition Software
 
C++11
C++11C++11
C++11
 
Checking WinMerge with PVS-Studio for the second time
Checking WinMerge with PVS-Studio for the second timeChecking WinMerge with PVS-Studio for the second time
Checking WinMerge with PVS-Studio for the second time
 
Memory management in C++
Memory management in C++Memory management in C++
Memory management in C++
 
PLSQL
PLSQLPLSQL
PLSQL
 
Web application architecture
Web application architectureWeb application architecture
Web application architecture
 
20 cool features that is in PHP 7, we missed in PHP 5. Let walkthrough with t...
20 cool features that is in PHP 7, we missed in PHP 5. Let walkthrough with t...20 cool features that is in PHP 7, we missed in PHP 5. Let walkthrough with t...
20 cool features that is in PHP 7, we missed in PHP 5. Let walkthrough with t...
 
Effective Java - Enum and Annotations
Effective Java - Enum and AnnotationsEffective Java - Enum and Annotations
Effective Java - Enum and Annotations
 
Lecture 2
Lecture 2Lecture 2
Lecture 2
 
C questions
C questionsC questions
C questions
 

Destacado

Oop06 6
Oop06 6Oop06 6
Oop06 6schwaa
 
Oop05 6
Oop05 6Oop05 6
Oop05 6schwaa
 
Oop02 6
Oop02 6Oop02 6
Oop02 6schwaa
 
Oop09 6
Oop09 6Oop09 6
Oop09 6schwaa
 
Oop07 6
Oop07 6Oop07 6
Oop07 6schwaa
 
Oop03 6
Oop03 6Oop03 6
Oop03 6schwaa
 
Oop04 6
Oop04 6Oop04 6
Oop04 6schwaa
 
Oop01 6
Oop01 6Oop01 6
Oop01 6schwaa
 

Destacado (9)

Oop06 6
Oop06 6Oop06 6
Oop06 6
 
Oop05 6
Oop05 6Oop05 6
Oop05 6
 
Oop02 6
Oop02 6Oop02 6
Oop02 6
 
Oop09 6
Oop09 6Oop09 6
Oop09 6
 
Oop07 6
Oop07 6Oop07 6
Oop07 6
 
Oop03 6
Oop03 6Oop03 6
Oop03 6
 
Oop04 6
Oop04 6Oop04 6
Oop04 6
 
Inheritance
InheritanceInheritance
Inheritance
 
Oop01 6
Oop01 6Oop01 6
Oop01 6
 

Similar a Oop10 6

6-Exception Handling and Templates.pptx
6-Exception Handling and Templates.pptx6-Exception Handling and Templates.pptx
6-Exception Handling and Templates.pptxSatyamMishra237306
 
Aae oop xp_13
Aae oop xp_13Aae oop xp_13
Aae oop xp_13Niit Care
 
OpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ ProgrammingOpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ ProgrammingOpen Gurukul
 
Lecture 4, c++(complete reference,herbet sheidt)chapter-14
Lecture 4, c++(complete reference,herbet sheidt)chapter-14Lecture 4, c++(complete reference,herbet sheidt)chapter-14
Lecture 4, c++(complete reference,herbet sheidt)chapter-14Abu Saleh
 
cbybalaguruswami-e-180803051831.pptx
cbybalaguruswami-e-180803051831.pptxcbybalaguruswami-e-180803051831.pptx
cbybalaguruswami-e-180803051831.pptxSRamadossbiher
 
cbybalaguruswami-e-180803051831.pptx
cbybalaguruswami-e-180803051831.pptxcbybalaguruswami-e-180803051831.pptx
cbybalaguruswami-e-180803051831.pptxSRamadossbiher
 
Exceptions ref
Exceptions refExceptions ref
Exceptions ref. .
 
Exception handling
Exception handlingException handling
Exception handlingIblesoft
 
UNIT III.ppt
UNIT III.pptUNIT III.ppt
UNIT III.pptAjit Mali
 
Handling Exceptions In C &amp; C++[Part A]
Handling Exceptions In C &amp; C++[Part A]Handling Exceptions In C &amp; C++[Part A]
Handling Exceptions In C &amp; C++[Part A]ppd1961
 
Object oriented programming system with C++
Object oriented programming system with C++Object oriented programming system with C++
Object oriented programming system with C++msharshitha03s
 
Lecture 09 Exception Handling(1 ) in c++.pptx
Lecture 09 Exception Handling(1 ) in c++.pptxLecture 09 Exception Handling(1 ) in c++.pptx
Lecture 09 Exception Handling(1 ) in c++.pptxZenLooper
 

Similar a Oop10 6 (20)

6-Exception Handling and Templates.pptx
6-Exception Handling and Templates.pptx6-Exception Handling and Templates.pptx
6-Exception Handling and Templates.pptx
 
Aae oop xp_13
Aae oop xp_13Aae oop xp_13
Aae oop xp_13
 
Exception
ExceptionException
Exception
 
OpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ ProgrammingOpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ Programming
 
Lecture 4, c++(complete reference,herbet sheidt)chapter-14
Lecture 4, c++(complete reference,herbet sheidt)chapter-14Lecture 4, c++(complete reference,herbet sheidt)chapter-14
Lecture 4, c++(complete reference,herbet sheidt)chapter-14
 
Namespaces
NamespacesNamespaces
Namespaces
 
$Cash
$Cash$Cash
$Cash
 
$Cash
$Cash$Cash
$Cash
 
cbybalaguruswami-e-180803051831.pptx
cbybalaguruswami-e-180803051831.pptxcbybalaguruswami-e-180803051831.pptx
cbybalaguruswami-e-180803051831.pptx
 
cbybalaguruswami-e-180803051831.pptx
cbybalaguruswami-e-180803051831.pptxcbybalaguruswami-e-180803051831.pptx
cbybalaguruswami-e-180803051831.pptx
 
Exceptions ref
Exceptions refExceptions ref
Exceptions ref
 
Exception handling
Exception handlingException handling
Exception handling
 
UNIT III.ppt
UNIT III.pptUNIT III.ppt
UNIT III.ppt
 
UNIT III (2).ppt
UNIT III (2).pptUNIT III (2).ppt
UNIT III (2).ppt
 
Handling Exceptions In C &amp; C++[Part A]
Handling Exceptions In C &amp; C++[Part A]Handling Exceptions In C &amp; C++[Part A]
Handling Exceptions In C &amp; C++[Part A]
 
Object oriented programming system with C++
Object oriented programming system with C++Object oriented programming system with C++
Object oriented programming system with C++
 
Lecture 09 Exception Handling(1 ) in c++.pptx
Lecture 09 Exception Handling(1 ) in c++.pptxLecture 09 Exception Handling(1 ) in c++.pptx
Lecture 09 Exception Handling(1 ) in c++.pptx
 
Unit iii
Unit iiiUnit iii
Unit iii
 
Exception handling
Exception handlingException handling
Exception handling
 
C++ aptitude
C++ aptitudeC++ aptitude
C++ aptitude
 

Oop10 6

  • 1. Object Oriented Programming Object Oriented Programming EXCEPTIONS Exceptions provide a systematic, object-oriented approach to handle runtime errors The problem with this approach is that every single call to such a function generated by C++ classes. must be examined by the program. To qualify as an exception, such errors must occur as a result of some action taken within a program and they must be the ones the program itself can discover. Surrounding each function call with an if...else statement and inserting For example, a constructor in a user-written string class might generate an exception statements to handle the error (or to call an error-handler routine) makes the if the application tries to initialize an object with a string that’s too long. listing long and hard to read. Similarly, a program can check if a file was opened or written successfully and Also, it’s not practical for some functions to return an error value. For example, generate an exception if it was not. imagine a min() function that returns the minimum of two values. All possible Let’s look at how the process was handled in the past. return values from this function represent valid outcomes. There’s no value left In C language programs, an error to use as an error return. if( somefunc() == ERROR RETURN VALUE ) ERROR_RETURN_VALUE is ft i often signaled b returning a i l d by t i // handle the error or call error-handler function The problem becomes more complex when classes are used because errors may particular value from the function else take place without a function being explicitly called. For example, suppose an in which it occurred. // proceed normally application defines objects of a class: For example, many math functions if( anotherfunc() == NULL ) return a special value to indicate // handle the error or call error-handler function SomeClass obj1, obj2, obj3; an error, and disk file functions else often return NULL or 0 to signal How will the application find out if an error occurred in the class constructor? // proceed normally an error. if( thirdfunc() == 0 ) The constructor is called implicitly, so there’s no return value to be checked. Each time you call one of these // handle the error or call error-handler function functions, you check the return else // proceed normally value. www.buzluca.info/oop ©1999-2008 Dr. Feza BUZLUCA 10.1 www.buzluca.info/oop ©1999-2008 Dr. Feza BUZLUCA 10.2 Object Oriented Programming Object Oriented Programming Exception Syntax Example; a fraction function: It takes the numerator and denominator as parameters, calculates the result of the fraction and returns it back. If an error is detected in a member function, this member function informs the If the denominator is zero an exception must be thrown. application that an error has occurred. When exceptions are used, this is called float fraction(int num, int denom) throwing an exception. { In the application, a separate section of code is installed to handle the error. This if(denom==0) throw "Divide by zero"; code is called an exception handler or catch block: it catches the exceptions return static_cast<float>(num) / denom; thrown by the member function. } Any code in the application that uses objects of the class is enclosed in a try block. int main() { The exception mechanism uses three new C++ keywords: throw, catch, and try. int numerator, denominator; Throwing an exception: cout << endl << "Enter the numerator ";; cin >> numerator; Syntax of a function f that throws an exception: cout << endl << "Enter the denominator "; return_type f( parameters ) { cin >> denominator; if ( exception_condition ) throw exceptioncode; try{ cout << fraction(numerator, denominator); // normal operation } return expression; catch (const char * result){ The catch block must immediately } cout << endl << result; follow the try block. Here exceptioncode can be any variable or constant of any built-in type (as } cout << endl << "End of Program"; char, int, char *) or it can also be an object that defines the exception. return 0; See Example: e10_1.cpp } www.buzluca.info/oop ©1999-2008 Dr. Feza BUZLUCA 10.3 www.buzluca.info/oop ©1999-2008 Dr. Feza BUZLUCA 10.4 Object Oriented Programming Object Oriented Programming In a catch block you may catch only the type of the exception-code, if the code If a function throws exceptions of different types, then a separate catch itself is not necessary. block must be written for each exception type. catch (const char *){ cout << endl << "ERROR"; // The thrown data is unknown try { } cout << fraction(numerator , denominator); } A function may throw more then one exceptions. For example if we don't catch (const char * result) { // Catch block for exceptions of type char * want negative denominators, we can write the fraction function as follows: cout << endl << result; float fraction(int num, int denom) } { catch (int) { // Catch block for exceptions of type int (value is not taken) if(denom == 0) throw "Divide by zero"; cout << endl << "ERROR"; if(denom < 0) throw "Negative denominator"; } See Example: e10_2.cpp return static_cast<float>(num) / denom; } A function may also throw exceptions of different types. Like built-in data types, objects can also be thrown and caught as exceptions. float fraction(int num, int denom) Examine the example e10_3.cpp. In this program we have a class: Stack. This { class includes two functions push and pop. If an error occurs, these functions if(denom == 0) throw "Divide by zero"; // throws char * throw an object of class Error. if(denom < 0) throw "Negative denominator"; // throws char * if(denom > 1000) throw -1; // throws int See Example: e10_3.cpp return static_cast<float>(num) / denom; } www.buzluca.info/oop ©1999-2008 Dr. Feza BUZLUCA 10.5 www.buzluca.info/oop ©1999-2008 Dr. Feza BUZLUCA 10.6 1
  • 2. Object Oriented Programming Object Oriented Programming int main() Exceptions are necessary to find out if an error occurred in the class { constructor. Constructors are called implicitly and there’s no return value to be char input[20]; // To take strings from keyboard checked. String *str; // Pointer to objects Example: The creator of the String class does not allow the contents of the bool again; // loop condition String to be longer than 10 characters. do{ class String{ again = false; enum { MAX_SIZE = 10 }; // MAX_SIZE is a constant cout << " Enter a string: "; int size; cin >> input; char *contents; try{ public: str= new String(input); // calls the constructor String(const char *); // Constructor } void print() const; // A member function catch (const char *){ ~String(); // Destructor cout << "String is too long" << endl; }; again = true; String::String(const char *in_data) } { }while(again); cout<< "Constructor has been invoked" << endl; str->print(); // The creation of the object is guaranteed size = strlen(in_data); delete str; if (size > MAX_SIZE) throw "String too long"; return 0; contents = new char[size +1]; // +1 for null character } strcpy(contents, in_data); The only way to exit the do-while loop is giving strings shorter than 10 } characters. Otherwise the object is not created. See Example: e10_4.cpp www.buzluca.info/oop ©1999-2008 Dr. Feza BUZLUCA 10.7 www.buzluca.info/oop ©1999-2008 Dr. Feza BUZLUCA 10.8 2