Exception Handling. C++ 2 Outline  Throwing and handling exceptions  Exceptions of different types  The new operator and the exceptions  Re-throwing.

Slides:



Advertisements
Similar presentations
C++ Basics Variables, Identifiers, Assignments, Input/Output.
Advertisements

Exception Handling Introduction Try Throw Catch. Exception Handling Use exception handling to write programs that are –Clearer –More robust –More fault-tolerant.
Exception Handling The purpose of exception handling is to permit the program to catch and handle errors rather than letting the error occur and suffer.
1 Chapter 17-2 Templates and Exceptions Dale/Weems.
CSE 332: C++ exceptions Overview of C++ Exceptions Normal program control flow is halted –At the point where an exception is thrown The program call stack.
CSIS 123A Lecture 11 Exception Handling. Introduction  Typical approach to development:  Write programs assuming things go as planned  Get ‘core’ working.
1 CSC241: Object Oriented Programming Lecture No 28.
Exception Handling. 2 Two types of bugs (errors) Logical error Syntactic error Logical error occur  due to poor understanding of the problem and solution.
Computer Science 1620 Loops.
Conditional Operator (?:) Conditional operator (?:) takes three arguments (ternary) Syntax for using the conditional operator:
Switch Switch case statements are a substitute for long if statements that compare a variable to several "integral" values ("integral" values are simply.
#include using namespace std; void main() { int a[3]={10,11,23}; for(int i=0;i
© Copyright Eliyahu Brutman Programming Techniques Course Version 1.0.
Exceptions. n Programmers have traditionally ignored the proper dedication of attention to error handling n Enclosing code inside countless nested-ifs.
General Computer Science for Engineers CISC 106 Lecture 33 Dr. John Cavazos Computer and Information Sciences 05/11/2009.
Introduction to C++ Templates and Exceptions l C++ Function Templates l C++ Class Templates l Exception and Exception Handler.
C++ Exceptions STL Vector. Example int Quotient (int numer, int denom} { if (denom != 0) return (numer/denom); else //What to do?? }
1 CSC241: Object Oriented Programming Lecture No 27.
M. Taimoor Khan #include void main() { //This is my first C++ Program /* This program will display a string message on.
Operator Overloading & Exception Handling TCP1201 OOPDS 1 Lecture 5 1.
Basic Concepts of OOP in C++ Darvay Zsolt. C++ 2 Outline  The namespace and its members  The using declaration and directive  The address operator.
Additional Control Structures. Chapter 9 Topics Switch Statement for Multi-way Branching Do-While Statement for Looping For Statement for Looping Using.
1 Chapter 9 Additional Control Structures Dale/Weems.
CHAPTER 7 arrays I NTRODUCTION T O C OMPUTER P ROGRAMMING (CSC425)
Variables and Data Types.  Variable: Portion of memory for storing a determined value.  Could be numerical, could be character or sequence of characters.
HANDLING EXCEPTIONS Chapter 9. Outline  Learn about the limitations of traditional error-handling methods  Throw exceptions  Use try blocks  Catch.
1 COMS 261 Computer Science I Title: Functions Date: October 12, 2005 Lecture Number: 17.
Exceptions in C++. Exceptions  Exceptions provide a way to handle the errors generated by our programs by transferring control to functions called handlers.
CSE 332: C++ Statements C++ Statements In C++ statements are basic units of execution –Each ends with ; (can use expressions to compute values) –Statements.
Exception Handling Outline 23.1 Introduction
Modular Programming – User Defined Functions. CSCE 1062 Outline  Modular programming – user defined functions  Value returning functions  return statement.
C++ Programming Lecture 13 Functions – Part V The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
LECTURE LECTURE 14 Exception Handling Textbook p
1 Chapter 17 Templates and Exceptions Dale/Weems.
1 Chapter 17 Templates and Exceptions Dale/Weems/Headington.
CS 11 C++ track: lecture 6 Today: Default function arguments friend classes Introduction to exception handling.
Classes class A { ... };.
1 For Loops l From Chapter 9 l A shorthand way of coding count loops.
Variables and memory addresses
1 Programming in C++ Dale/Weems/Headington Chapter 9 Additional Control Structures (Switch, Do..While, For statements)
Manipulator example #include int main (void) { double x = ; streamsize prec = cout.precision(); cout
A FIRST BOOK OF C++ CHAPTER 14 THE STRING CLASS AND EXCEPTION HANDLING.
C++ Basics Programming. COMP104 Lecture 5 / Slide 2 Introduction to C++ l C is a programming language developed in the 1970s with the UNIX operating system.
1 CSC 1111 Introduction to Computing using C++ C++ Basics (Part 1)
C++ Namespaces, Exceptions CSci 588: Data Structures, Algorithms and Software Design All material not from online sources copyright © Travis Desell, 2011.
Exception Handling How to handle the runtime errors.
Templates. C++ 2 Outline Function templates  Function template definition  Function template overloading Class templates  Class template definition.
Introduction to C++ Templates and Exceptions C++ Function Templates C++ Class Templates Exception and Exception Handler.
C++ Programming Lecture 13 Functions – Part V By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
Introduction to C++ programming Recap- session 1 Structure of C++ program Keywords Operators – Arithmetic – Relational – Logical Data types Classes and.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Asif Nawaz University Institute of Information Technology, PMAS-AAUR Lecture 05: Object Oriented Programming:2014 Object-Oriented Programming in C++ Exception.
C++ Lesson 1.
C ++ MULTIPLE CHOICE QUESTION
Exceptions Error Handling and Recovery
Topics: Templates Exceptions
Pointers and Dynamic Arrays
Why exception handling in C++?
Programming Fundamentals
EXCEPTION HANDLING.
group work #hifiTeam
Reserved Words.
Dynamic Memory Allocation Reference Variables
CSC 270 – Survey of Programming Languages
Exception Handling.
Exceptions 1 CMSC 202.
Object-Oriented Programming (OOP) Lecture No. 43
Object-Oriented Programming (OOP) Lecture No. 44
Programming Fundamental
CMSC 202 Lesson 20 Exceptions 1.
Presentation transcript:

Exception Handling

C++ 2 Outline  Throwing and handling exceptions  Exceptions of different types  The new operator and the exceptions  Re-throwing an exception

C++ 3 Throwing and Handling Exceptions  We throw an exception when we want to postpone the effect of an event (which is probably an error).  In order to accomplish this we use the throw statement.  After the throw keyword we have to give an expression (a constant or a variable or maybe an object).  Exception handling can be done using the try and catch blocks.

C++ 4 The try and catch Blocks  The try - catch construction: try compound-statement handler-sequence  The handler-sequence is composed of one or more handlers. Each handler has the form: catch(exception-declaration) compound-statement  The exception-declaration is similar to the formal parameters of functions.

C++ 5 Example  The MyVector class with exception handling in the Sum member function.

C++ 6 The Class Declaration class MyVector { private: int *elem; int dim; public: MyVector(int *e, int d); MyVector(const MyVector & v); ~MyVector(); void SquareVect(); MyVector Sum(MyVector & v); void Display(); };

C++ 7 The Copy Constructor MyVector::MyVector(const MyVector & v) { dim = v.dim; elem = new int[dim]; for(int i=0; i < dim; i++) elem[i] = v.elem[i]; }

C++ 8 The Sum Member Function MyVector MyVector::Sum(MyVector & v) { if (dim != v.dim) throw "Different size"; int* x = new int[dim];

C++ 9 The Sum Member Function for(int i = 0; i < dim; i++) x[i] = elem[i] + v.elem[i]; MyVector t(x, dim); delete [] x; return t; }

C++ 10 The main Function (VectX) int main() { int x[20]; int dimX; cout << "dimension of X = "; cin >> dimX; for(int i = 0; i < dimX; i++) x[i] = 2 * i + 1; MyVector VektX(x, dimX); cout << "the X vector : "; VektX.Display();

C++ 11 VectY int y[20]; int dimY; cout << "dimension of Y = "; cin >> dimY; for(int i = 0; i < dimY; i++) y[i] = 2 * i + 2; MyVector VektY(y, dimY); cout << "the Y vector : "; VektY.Display();

C++ 12 The try and catch Blocks try { cout << "sum of vectors: "; VektX.Sum(VektY).Display(); cout << "No error\n"; } catch(const char *s) { cout << "Error! " << s << endl; }

C++ 13 Output (the same size) dimension of X = 2 the X vector : 1 3 dimension of Y = 2 the Y vector : 2 4 sum of vectors: 3 7 No error

C++ 14 Output (different size) dimension of X = 2 the X vector : 1 3 dimension of Y = 3 the Y vector : sum of vectors: Error! Different size

C++ 15 Exceptions of Different Types  We can have multiple catch blocks after a try block.  To catch everything use: catch (... ) compound-statement  The... is part of the syntax.  The order of the catch blocks is important!

C++ 16 Example #include using namespace std;

C++ 17 The Print_Nonzero Function template void Print_Nonzero(T x) { if ( x == static_cast (0) ) throw static_cast (0); cout << typeid(x).name() << " " << x << endl; }

C++ 18 The main Function int main() { srand( (unsigned)time( NULL ) ); //...

C++ 19 The try Block try { switch ( rand() % 5 ) { case 0: Print_Nonzero( static_cast ( rand() % 2 ) ); break; case 1: Print_Nonzero( static_cast ( rand() % 2 ) ); break;

C++ 20 The try Block case 2: Print_Nonzero( static_cast ( rand() % 2 ) ); break; default: Print_Nonzero( rand() % 2 ); break; }

C++ 21 Catch Blocks catch( int ) { cout << "Error: zero (int)\n"; } catch( long ) { cout << "Error: zero (long)\n"; } catch(... ) { cout << "Error: zero (floating point)\n"; }

C++ 22 The new Operator and the Exceptions  If there isn’t enough memory then  in older versions of C++ the new operator simply returned zero  at present (C++ standard) throws a std::bad_alloc exception, but if we don’t want to occur this, then we have to use the form new(std::nothrow).

C++ 23 Re-throwing an Exception  Use the throw; statement in the catch block.

C++ 24 Empty Class #include using namespace std; class DivisionByZero{}; // use it only // for handling exceptions

C++ 25 The f Function double f(double x) { if ( x == 0.0 ) throw DivisionByZero(); return 1.0 / x; }

C++ 26 The g Function double g(char *s, double x) { double y = 0.0; cout << s; try { y = f(x); }

C++ 27 The g Function catch( DivisionByZero ) { cout << "Error in g: "; //throw; } return y; }

C++ 28 The main function int main() { double number; cout << "The number = "; cin >> number; try { cout << g("The inverse: ", number) << endl; } catch( DivisionByZero ) { cout << "Division by zero.\n"; }

C++ 29 Output The number = 0 The inverse: Error in g: 0  But if we re-throw the exception (uncomment throw in function g), then: The number = 0 The inverse: Error in g: Division by zero.