Exceptions. Why Exception Handling?

Similar documents
21. Exceptions. Advanced Concepts: // exceptions #include <iostream> using namespace std;

ECE 122. Engineering Problem Solving with Java

Exception with arguments

C++ Exception Handling 1

Object Oriented Programming

Introduction. Common examples of exceptions

CPSC 427: Object-Oriented Programming

Object Oriented Programming

IS 0020 Program Design and Software Tools

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Exceptions, Case Study-Exception handling in C++.

Object-Oriented Programming (OOP) Fundamental Principles of OOP

Le L c e t c ur u e e 5 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Exception Handling

C++ TEMPLATES. Templates are the foundation of generic programming, which involves writing code in a way that is independent of any particular type.

Exceptions (part 2) An exception is an object that describes an unusual or erroneous situation. Quick Review of Last Lecture.

CSC 330. An Exception is. Handling Exceptions. Error Handling. Assertions. C++ Exception. Example

Exam 1 is on Wednesday 10 / 3 / 2018

C++ PROGRAMMING LANGUAGE: DYNAMIC MEMORY ALLOCATION AND EXCEPTION IN C++. CAAM 519, CHAPTER 15

Exception Handling Pearson Education, Inc. All rights reserved.

COMP6771 Advanced C++ Programming

2. How many runtime error messages associated with exception? a) 2 b) 4 c) 5 d) infinite

05-01 Discussion Notes

CS11 Introduction to C++ Fall Lecture 6

CS11 Advanced C++ Fall Lecture 3

Operators. The Arrow Operator. The sizeof Operator

C++ Namespaces, Exceptions

Introduction to Java. Handout-3a. cs402 - Spring

Programming II (CS300)

Advanced Flow of Control -- Introduction

Exception-Handling Overview

Exception handling. Aishy Amer. Lecture Outline: Introduction Types or errors or exceptions Conventional error processing Exception handling in C++

CSI33 Data Structures

Laboratorio di Tecnologie dell'informazione

C++ Exception Handling. Dr. Md. Humayun Kabir CSE Department, BUET

G52CPP C++ Programming Lecture 16

Exception Handling in C++

C++ Programming Fundamentals

Programming II (CS300)

Chapter 10. Exception Handling. Java Actually: A Comprehensive Primer in Programming

COMP322 - Introduction to C++ Lecture 10 - Overloading Operators and Exceptions

Chapter 13 Exception Handling

mywbut.com Exception Handling

COMP1008 Exceptions. Runtime Error

CSC 330 Object-Oriented Programming. Exception Handling CSC 330

Pointers, Dynamic Data, and Reference Types

CS Programming I: Exceptions

CPSC 427: Object-Oriented Programming

CS558 Programming Languages

CS Programming I: Exceptions

Introduction. Exceptions: An OO Way for Handling Errors. Common Runtime Errors. Error Handling. Without Error Handling Example 1

Exception Handling. Sometimes when the computer tries to execute a statement something goes wrong:

Integer Data Types. Data Type. Data Types. int, short int, long int

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Chapter 17 vector and Free Store

Exception Handling. Run-time Errors. Methods Failure. Sometimes when the computer tries to execute a statement something goes wrong:

Introduction to Software Design

Homework 4. Any questions?

The format for declaring function templates with type parameters

CPSC 427: Object-Oriented Programming

Variable Definitions and Scope

Administration. Exceptions. Leftovers. Agenda. When Things Go Wrong. Handling Errors. CS 99 Summer 2000 Michael Clarkson Lecture 11

int main() { int account = 100; // Pretend we have $100 in our account int withdrawal;

CS 3 Introduction to Software Engineering. 3: Exceptions

Exception Handling Pearson Education, Inc. All rights reserved.

JAC444 - Lecture 4. Segment 1 - Exception. Jordan Anastasiade Java Programming Language Course

Object Oriented Programming CS250

! Errors can be dealt with at place error occurs

Introduction to Programming Using Java (98-388)

CPSC 427: Object-Oriented Programming

void fun() C::C() // ctor try try try : member( ) catch (const E& e) { catch (const E& e) { catch (const E& e) {

COM S 213 PRELIM EXAMINATION #2 April 26, 2001

Debugging and Profiling

Exceptions, Templates, and the STL

vector and Free Store

Lecture Material. Exceptions

6.Introducing Classes 9. Exceptions

Variables. Data Types.

Lecture 10. To use try, throw, and catch Constructors and destructors Standard exception hierarchy new failures

2 nd Week Lecture Notes

Chapter 9. Operator Overloading. Dr Ahmed Rafat

COMP-202. Exceptions. COMP Exceptions, 2011 Jörg Kienzle and others

Lecture 20. Java Exceptional Event Handling. Dr. Martin O Connor CA166

Object Oriented Programming Exception Handling

BBM 102 Introduction to Programming II Spring Exceptions

CS313D: ADVANCED PROGRAMMING LANGUAGE

! An exception is a condition that occurs at execution time and makes normal continuation of the program impossible.

CS558 Programming Languages

About This Lecture. Outline. Handling Unusual Situations. Reacting to errors. Exceptions

Exception Handling in Java. An Exception is a compile time / runtime error that breaks off the

Programming Languages Third Edition. Chapter 9 Control I Expressions and Statements

Internal Classes and Exceptions

Laboratorio di Tecnologie dell'informazione. Ing. Marco Bertini

Programming in C++: Assignment Week 8

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Chapter 17 vector and Free Store

CS240: Programming in C

CSC Java Programming, Fall Java Data Types and Control Constructs

Harvard School of Engineering and Applied Sciences CS 152: Programming Languages

JAYARAM COLLEGE OF ENGINEERING AND TECHNOLOGY Pagalavadi, Tiruchirappalli (An approved by AICTE and Affiliated to Anna University)

Lecture 9: Parameter Passing, Generics and Polymorphism, Exceptions

Transcription:

Exceptions An exception is an object that stores information transmitted outside the normal return sequence. It is propagated back through calling stack until some function catches it. If no calling function catches the exception, the program terminates. Why? Exceptions are anomalies that occur during the normal flow of a program and prevent it from continuing. These anomalies--user, logic, or system errors--can be detected by a function. If the detecting function cannot deal with the anomaly, it throws, an exception. A function that handles that kind of exception catches it. In C++, when an exception is thrown, it cannot be ignored--there must be some kind of notification or termination of the program. If no user-provided exception handler is present, the compiler provides a default mechanism to terminate the program. Exception handling is expensive compared to ordinary program flow controls, such as loops or if-statements. It is therefore better not to use the exception mechanism to deal with ordinary situations, but to reserve it for situations that are truly unusual. For example, a function might have the job of opening a file and initializing some associated data. If the file cannot be opened or is corrupted, the function cannot do its job. However, that function might not have enough information to handle the problem. The function can throw an exception object that describes the problem, transferring control to an earlier point in the program. The exception handler might automatically try a backup file, query the user for another file to try, or shut down the program gracefully. Without exception handlers, status and data would have to be passed down and up the function call hierarchy, with status checks after every function call. With exception handlers, the flow of control is not obscured by error checking. If a function returns, the caller can be certain that it succeeded. Fall 2018 Husain Gholoom Lecturer in Computer Science Page 1

Using ( try catch ) There are three keywords for exception handling in C++: try throw catch try A try block is a group of C++ statements, normally enclosed in braces, which may cause an exception. This grouping restricts exception handlers to exceptions generated within the try block. throw The throw statement is used to throw an exception to a subsequent exception handler. A throw statement is specified with: The keyword throw. An assignment expression; the type of the result of the expression determines which catch exception handler receives control catch A catch block is a group of C++ statements that are used to handle a specific raised exception. Catch blocks, or handlers, should be placed after each try block. A catch block is specified by: The keyword catch A catch expression, which corresponds to a specific type of exception that may be thrown by the try block A group of statements, enclosed in braces, whose purpose is to handle the exception Fall 2018 Husain Gholoom Lecturer in Computer Science Page 2

Example - 1 double division(int a, int b) if (b == 0) throw "Division by zero condition!"; return (a / b); int main() int x = 50; int y = 0; double z = 0; try z = division(x, y); cout << z << endl; catch (const char* msg) cout << msg << endl; Division by zero condition! Fall 2018 Husain Gholoom Lecturer in Computer Science Page 3

Example 2 int main() int x = - 1; // Some code cout << "Before try \n"; try cout << "Inside try \n"; if (x < 0) throw x; cout << "After throw (Never executed) \n"; catch (int x ) cout << "Exception Caught \n"; cout << "After catch (Will be executed) \n"; Before try Inside try Exception Caught After catch (Will be executed) Fall 2018 Husain Gholoom Lecturer in Computer Science Page 4

There is a special catch block called catch all catch( ) that can be used to catch all types of exceptions. For example, in the following program, an int is thrown as an exception, but there is no catch block for int, so catch( ) block will be executed Example 3 int main() try throw "a"; catch (char *exception) cout << "Caught " << exception; catch (...) cout << "Default Exception\n"; Caught a Fall 2018 Husain Gholoom Lecturer in Computer Science Page 5

Example 4 int main() try throw 10; catch (char *exception) cout << "Caught " << exception; catch (...) cout << "Default Exception\n"; Default Exception Fall 2018 Husain Gholoom Lecturer in Computer Science Page 6

Implicit type conversion doesn t happen for primitive types. For example, in the following program a is not implicitly converted to int Example 5 int main() try throw 'a'; catch (int x) cout << "Caught " << x; catch (...) cout << "Default Exception\n"; Default Exception Fall 2018 Husain Gholoom Lecturer in Computer Science Page 7

If an exception is thrown and not caught anywhere, the program terminates abnormally. For example, in the following program, a char is thrown, but there is no catch block to catch a char. Example 6 int main() try throw 'a'; catch (int x) cout << "Caught "; terminate called after throwing an instance of 'char' 0 [main] trycatchexample 5704 cygwin_exception::open_stackdumpfile: Dumping stack trace to trycatchexample.exe.stackdump Fall 2018 Husain Gholoom Lecturer in Computer Science Page 8

Dynamic Allocation Example 7 int main () try char * mystring; mystring = new char [10]; if (mystring == NULL) throw "Allocation failure"; for (int n=0; n<=100; n++) if (n>9) throw n; mystring[n]='z'; cout << mystring[n] << " "; catch (int i) cout << "\n\nexception: "; cout << "index " << i << " is out of range" << endl; catch (char * str) cout << "\n\nexception: " << str << endl; z z z z z z z z z z Exception: index 10 is out of range Fall 2018 Husain Gholoom Lecturer in Computer Science Page 9

Example 8 int main () try char * mystring; mystring = NULL; if (mystring == NULL) throw "Allocation failure"; for (int n=0; n<=100; n++) if (n>9) throw n; mystring[n]='z'; cout << mystring[n] << " "; catch (int i) cout << "\n\nexception: "; cout << "index " << i << " is out of range" << endl; catch (char * str) cout << "\n\nexception: " << str << endl; Exception: Allocation failure Fall 2018 Husain Gholoom Lecturer in Computer Science Page 10

What is the output of the following program #include<iostream> int main() try throw(55.5); throw('i'); catch (int e) cout << "Input is Integer value " << e << endl; catch (double e) cout << "Input is Double value " << e << endl; catch (char e) cout << "Input is Character " << e << endl; Fall 2018 Husain Gholoom Lecturer in Computer Science Page 11

in Vectors - 1 #include <vector> int main() /* Initialize vector of 10 copies of the integer 5 */ vector<int> vectorone(10,5); cout<< "Display elements of vector - unsafe code " << endl << endl; for (int index=0; index< 15; ++index) cout << vectorone[index] << " " ; return EXIT_SUCCESS; Display elements of vector - unsafe code 5 5 5 5 5 5 5 5 5 5 0 51 1629486856-552734650 537269376 Fall 2018 Husain Gholoom Lecturer in Computer Science Page 12

in Vectors - 2 #include <vector> int main() /* Initialize vector of 10 copies of the integer 5 */ vector<int> vectorone(10,5); cout<< "Display elements of vector - unsafe code - runtime error " << endl << endl; for (long index=0; index<20; ++index) cout << "Element " << index << ": " << vectorone.at(index) << endl; cout<<endl<<endl; Display elements of vector - unsafe code - runtime error Element 0: 5 Element 1: 5 Element 2: 5 Element 3: 5 Element 4: 5 Element 5: 5 Element 6: 5 Element 7: 5 Element 8: 5 Element 9: 5 terminate called after throwing an instance of 'std::out_of_range' what(): vector::_m_range_check 0 [main] trycatchexample 552 cygwin_exception::open_stackdumpfile: Dumping stack trace to trycatchexample.exe.stackdump Fall 2018 Husain Gholoom Lecturer in Computer Science Page 13

in Vectors - 3 #include <vector> int main() /* Initialize vector of 10 copies of the integer 5 */ vector<int> vectorone(10,5); cout<< "Display the elements of vector - safe code " << endl << endl; // run through the vector and display each element, if possible for (long index=0; index<20; ++index) try cout << "Element " << index << ": " << vectorone.at(index) << endl; catch (exception& e) cout << "Element " << index << ": index exceeds vector dimensions." << endl; return 0 ; Fall 2018 Husain Gholoom Lecturer in Computer Science Page 14

Display the elements of vector - safe code Element 0: 5 Element 1: 5 Element 2: 5 Element 3: 5 Element 4: 5 Element 5: 5 Element 6: 5 Element 7: 5 Element 8: 5 Element 9: 5 Element 10: index exceeds vector dimensions. Element 11: index exceeds vector dimensions. Element 12: index exceeds vector dimensions. Element 13: index exceeds vector dimensions. Element 14: index exceeds vector dimensions. Fall 2018 Husain Gholoom Lecturer in Computer Science Page 15