Exceptions. Why exceptions? We often strive for writing portable reusable code; we are able to detect errors, however our code may be used for many different.

Slides:



Advertisements
Similar presentations
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy.
Advertisements

 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 13 - Exception Handling Outline 13.1 Introduction 13.2 Exception-Handling Overview 13.3 Other.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide
Lecture 9. 2 Exception  An exception is a unusual, often unpredictable event, detectable by software or hardware, that requires special processing occurring.
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
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.
Exceptions, Templates, And The Standard Template Library (STL) Chapter 16.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 16 Exception Handling.
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.
Copyright © 2012 Pearson Education, Inc. Chapter 16: Exceptions, Templates, and the Standard Template Library (STL)
Error Handling with Exceptions Concepts C and other earlier languages often had multiple error-handling schemes, and these were generally established.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 16: Exception Handling.
Lesson 16 Exceptions Lesson Exceptions1. Murphy’s Law Anything that can go wrong will go wrong Lesson Exceptions2.
1 Lecture 11 Interfaces and Exception Handling from Chapters 9 and 10.
Exception Handling Introduction Exception handling is a mechanism to handle exceptions. Exceptions are error like situations. It is difficult to decide.
CS Advanced C++ Exception Handling Topic #5.
Exceptions (Large parts of these copied from Ed Schonberg’s slides)
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Exceptions. Errors and Exceptions An error is a bug in your program –dividing by zero –going outside the bounds of an array –trying to use a null reference.
© Copyright Eliyahu Brutman Exceptions. © Copyright Eliyahu Brutman Exceptions and Design Patterns - 2 Introduction to Exception Handling Definition:
Exception Handling An Exception is an indication of a problem that occurs during a program’s execution. Exception handling enables the programmer to create.
© Copyright Eliyahu Brutman Programming Techniques Course Version 1.0.
Exceptions. 2 Objectives Introduce C# exception handling –library exception types –custom exceptions Describe keywords used for exception handling –try.
Exceptions Objectives At the conclusion of this lesson, students should be able to Explain the need for exceptions Correctly write programs that use.
計算機概論實習 A Simple Way to Handle Error if(b != 0) { cout
1 Chapter Eight Exception Handling. 2 Objectives Learn about exceptions and the Exception class How to purposely generate a SystemException Learn about.
Object Oriented Programming
Handling ErrorstMyn1 Handling Errors Up to this point we haven't worried much about errors or exceptions. First, let's distinguish between errors and exceptions.
Chapter 12: Exception Handling
UNIT 3 TEMPLATE AND EXCEPTION HANDLING. Introduction  Program errors are also referred to as program bugs.  A C program may have one or more of four.
1 CSC241: Object Oriented Programming Lecture No 27.
WEEK EXCEPTION HANDLING. Syntax Errors Syntax errors, also known as parsing errors, are perhaps the most common kind of complaint you get while.
Exception Handling. 2 Two types of bugs (errors) Logical error Syntactic error Logical error occur  Due to poor understanding of the problem and solution.
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
BIO Java 1 Exception Handling Aborting program not always a good idea – can’t lose messages – E-commerce: must ensure correct handling of private.
Classes In C++ 1. What is a class Can make a new type in C++ by declaring a class. A class is an expanded concept of a data structure: instead of holding.
Exception Handling Programmers must deal with errors and exceptional situations: User input errors Device errors Empty disk space, no memory Component.
COP4020 Programming Languages Exception Handling Prof. Robert van Engelen (modified by Prof. Em. Chris Lacher)
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 in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
Exceptions and Program Correctness based on the original work by Dr. Roger deBry Version 1.1.
Exception Handling Outline 23.1 Introduction
Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of.
CSCI 383 Object-Oriented Programming & Design Lecture 20 Martin van Bommel.
LECTURE LECTURE 14 Exception Handling Textbook p
Copyright © Curt Hill Error Handling in Java Throwing and catching exceptions.
Firoze Abdur Rakib. Syntax errors, also known as parsing errors, are perhaps the most common kind of error you encounter while you are still learning.
CMSC 202 Computer Science II for Majors. CMSC 202UMBC Topics Exceptions Exception handling.
JavaScript and Ajax (Control Structures) Week 4 Web site:
Exception Handling How to handle the runtime errors.
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
1 Handling Errors and Exceptions Chapter 6. 2 Objectives You will be able to: 1. Use the try, catch, and finally statements to handle exceptions. 2. Raise.
Section 3.3 Exceptional Situations. 3.3 Exceptional Situations Exceptional situation Associated with an unusual, sometimes unpredictable event, detectable.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
C++ Exceptions.
Exceptions.
Why exception handling in C++?
Part IX Fundamentals of C and C++ Programming Exception Handling
Exceptions with Functions
Chapter 17 Templates and Exceptions Part 2
Throwing and catching exceptions
Exceptions and Templates
Exceptions.
Exception Handling.
Programming in C# CHAPTER - 7
Problems Debugging is fine and dandy, but remember we divided problems into compile-time problems and runtime problems? Debugging only copes with the former.
Object-Oriented Programming (OOP) Lecture No. 44
CMSC 202 Exceptions.
Presentation transcript:

Exceptions

Why exceptions? We often strive for writing portable reusable code; we are able to detect errors, however our code may be used for many different purposes and we are not able to foresee how to react when error occurs. We often strive for writing portable reusable code; we are able to detect errors, however our code may be used for many different purposes and we are not able to foresee how to react when error occurs. Someone that uses our code has a quite opposite problem – he knows what to do when the error is detected, however in detecting and signaling errors he’d like to depend on our code. Someone that uses our code has a quite opposite problem – he knows what to do when the error is detected, however in detecting and signaling errors he’d like to depend on our code.

Exceptions in C++ In C++ the exception mechanism is introduced, as a method of signaling errors when the errors are detected and a method of defining reactions – code to be executed, when the error is detected. C++ exception mechanism uses following keywords: catch throw and try. In C++ the exception mechanism is introduced, as a method of signaling errors when the errors are detected and a method of defining reactions – code to be executed, when the error is detected. C++ exception mechanism uses following keywords: catch throw and try. throw — raising exception (signaling, that the error has been detected) throw — raising exception (signaling, that the error has been detected) try — precedes the code (placed in curly brackets) that may raise exceptions try — precedes the code (placed in curly brackets) that may raise exceptions catch — defines the reaction for errors /exceptions/ raised in preceding try. catch — defines the reaction for errors /exceptions/ raised in preceding try.

throw, try and catch double function()// function that may detect errors // and signal it // and signal it // by raising exceptions // by raising exceptions{ // calculations // calculations // in case of detecting the error // in case of detecting the error throw 1; // we raise exception throw 1; // we raise exception // otherwise we continue processing // otherwise we continue processing // if other error is detected // if other error is detected throw 2; // raise another exception throw 2; // raise another exception //... //...}

void example0() { try// we’ll be doing something try// we’ll be doing something // that may raise exception // that may raise exception { // curly bracket obligatory here! { // curly bracket obligatory here! function(); function(); cout << „no errors :-) "; cout << „no errors :-) "; } catch (int i) // if the exception was raised catch (int i) // if the exception was raised // the following code will be executed // the following code will be executed // (exception handler) // (exception handler) {// curly bracket obligatory here! {// curly bracket obligatory here! cout << „error detected " << i; cout << „error detected " << i; } // in case function() ends without raising any exception // in case function() ends without raising any exception // exception handler is skipped // exception handler is skipped // and code following exception handler is executed // and code following exception handler is executed cout << „example 0 ends "; cout << „example 0 ends ";}

throw, try and catch throw – it’s an operator, that is followed by expression determining type(class) and value of the exception. We may define various classes of exceptions; throw – it’s an operator, that is followed by expression determining type(class) and value of the exception. We may define various classes of exceptions; catch – may follow throw or another catch{...} only, in the parenthesis we specify type(class) of the exception and variable(object) that holds value of the exception. catch – may follow throw or another catch{...} only, in the parenthesis we specify type(class) of the exception and variable(object) that holds value of the exception. If knowledge of the class of the exception is enough to handle the exception we may specify the class only (without specifying the object). If knowledge of the class of the exception is enough to handle the exception we may specify the class only (without specifying the object). Code that handles exception is called the exception handler. Code that handles exception is called the exception handler. Exception handler may be placed even in the very method/function that raises the exception. Exception handler may be placed even in the very method/function that raises the exception.

void example1() { try try { // some calculations and error // some calculations and error throw ‘a’; throw ‘a’; // other calculations and error again // other calculations and error again throw 1; throw 1; //... //... } catch (int i) catch (int i) { cout << „error detected, error number: " << i; cout << „error detected, error number: " << i; } catch (char) catch (char) { cout << „error detected"; cout << „error detected"; }}

Raising and catching exceptions When the exception is raised, the function call stack is analyzed from current function/method up to the main(). When the exception is raised, the function call stack is analyzed from current function/method up to the main(). When going up, local objects are being destructed (as if the function was exited normally). When going up, local objects are being destructed (as if the function was exited normally). If no exception handler is found (more then one handler may be defined) the program is stopped. If no exception handler is found (more then one handler may be defined) the program is stopped. If matching handler is found (matching the class of exception) then it’s executed. If there were couple matching handlers first found is executed. If matching handler is found (matching the class of exception) then it’s executed. If there were couple matching handlers first found is executed.

Raising and catching exceptions void example2() { try try { example0(); example0(); } catch (int i) catch (int i) { cout << „error detected, error code: " << i; cout << „error detected, error code: " << i; // this exception may be raised by example0(), // this exception may be raised by example0(), // but if raised, gets handled in example0() // but if raised, gets handled in example0() // so this code is never reached // so this code is never reached }}

Re-raising exceptions Exception is considered handled, in the moment we enter the exception handler code, following code is not an infinite loop: Exception is considered handled, in the moment we enter the exception handler code, following code is not an infinite loop: try try { // here we throw exception of class xxx { // here we throw exception of class xxx } catch (xxx) catch (xxx) { // we fail to handle it { // we fail to handle it throw xxx; // let’s raise it again, someone „up” may handle it throw xxx; // let’s raise it again, someone „up” may handle it } throw without an argument causes re-raising the same exception. throw without an argument causes re-raising the same exception.... so instead of „throw xxx;” we may write „throw;”.... so instead of „throw xxx;” we may write „throw;”.

Nested handlers try { // this code may raise exception of class zzz } catch (zzz) { try // we handle it try // we handle it { // however handling code may fail // however handling code may fail // and raise another exception of class zzz // and raise another exception of class zzz throw; // equivalent to „throw zzz;”, throw; // equivalent to „throw zzz;”, } catch (zzz) catch (zzz) { // handling exception raised while handling exception { // handling exception raised while handling exception }}

Exception classes We may define many classes of exceptions, or use already existing classes. We may define many classes of exceptions, or use already existing classes. In class libraries using exception mechanism we usually define special exception classes to distinguish different exceptions. In class libraries using exception mechanism we usually define special exception classes to distinguish different exceptions. Using own classes of exceptions is convenient, even the exception class name may be a clear information on kind of error detected. Using own classes of exceptions is convenient, even the exception class name may be a clear information on kind of error detected.

Exception classes Example: exception class: divide by zero Example: exception class: divide by zero class divide_by_0 {}; in case of error we use constructor in case of error we use constructor throw divide_by_0(); and catch the exception: and catch the exception: catch (divide_by_0) { /*... */ } In the above example we used class (not an object, using argument constructors we may pass to the exception handler further information on the error detected) In the above example we used class (not an object, using argument constructors we may pass to the exception handler further information on the error detected)

Inheritance of exception classes Dealing with exceptions we may benefit from inheritance – exception handler of exception of the base class handles also exceptions of the derived classes (automatic conversion, if the base was public: base). Dealing with exceptions we may benefit from inheritance – exception handler of exception of the base class handles also exceptions of the derived classes (automatic conversion, if the base was public: base). class math_error {}; class overflow:public math_error {}; class underflow:public math_error {}; class divide_by_0:public math_error {};

In case there are many handlers, first matching one met is executed (the one closest to try). In case there are many handlers, first matching one met is executed (the one closest to try).try{ throw overflow(); throw overflow();} catch(overflow) // handler for overflow {// and exceptions derived from overflow cout << "\noverflow"; cout << "\noverflow";} catch(math_error) // handler math errors { // except the overflow cout << "\nme"; // and ones derived from overflow cout << "\nme"; // and ones derived from overflow} Inheritance of exception classes

Wrong example : Wrong example :try{ throw overflow(); throw overflow();} catch(math_error) // handler math errors { // except the overflow cout << "\nme"; // and ones derived from overflow cout << "\nme"; // and ones derived from overflow} catch(overflow) // formally handler for overflow {// and exceptions derived from overflow // actually never reached since this exception // gets caught by above handler cout << "\noverflow"; cout << "\noverflow";} Inheritance of exception classes

Handling unhandled exceptions Using catch(...) we define handler for every exception Using catch(...) we define handler for every exception void m() { try try { // something // something } catch(...) catch(...) { // something went wrong, so do clean-up after the aborted m() // something went wrong, so do clean-up after the aborted m() throw; // and re-raise exception throw; // and re-raise exception }}

Specifying explicitly methods that throw exceptions void C::met() throw(int) { // something throw(12); throw(12); // something } It’s not obligatory It’s not obligatory It’s useful for user of met() It’s useful for user of met()

Specifying explicitly methods that do not throw exceptions void C::met() throw() { // something // throw not allowed here! // throw not allowed here! // something }