Exception Handling in C++

Exception Handling in C++
Slide Note
Embed
Share

Exception handling in C++ is a crucial aspect of programming, allowing for effective error resolution in various situations. By isolating error-checking code from main program logic, clarity, modifiability, and fault tolerance are improved. Learn about the benefits, implementation, and best practices of exception handling in C++ through examples and explanations.

  • C++
  • Exception Handling
  • Error Checking
  • Programming Languages
  • Fault Tolerance

Uploaded on Feb 19, 2025 | 0 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

You are allowed to download the files provided on this website for personal or commercial use, subject to the condition that they are used lawfully. All files are the property of their respective owners.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author.

E N D

Presentation Transcript


  1. Exception Handling Andy Wang Object Oriented Programming in C++ COP 3330

  2. Exception Handling A type of error checking, available in many programming languages Exception Some sort of problem or error that occurs during a program s execution Many error situations could occur besides those that we usually check for (usually related to things like user input) Exception handler A piece of code that resolves an exception situation Typical error check often intermixed with the tasks of a program (if statements, etc) Exception handlers are intended to be separate from the main tasks

  3. Why? Intermixing program logic with the error-checking code can sometimes make programs hard to read, debug, etc. Many potential problems are very infrequent Exception handlers are separate from main tasks of a program Can improve clarity and modifiability Exception handling can improve a program s fault tolerance

  4. When? This does not mean that exception handlers should be used in all cases Sometimes conventional error checking is more appropriate Exception handling best for problems that occur infrequently Errors that will result in termination of the program Not for user input checking Good for setting up uniform techniques for error handling when many programmers and multiple modules are involved

  5. How? Reserved words in C++: try throw, catch try blocks Consists of keyword try and a block of code inside { } Encloses the statements that might cause exceptions catch blocks 1+ catch blocks follow a try block (also in { }) Each catch block is an exception handler A cache block has a single parameter (with type listed)

  6. How? If an exception occurs in a try block The try block immediately ends Program attempts to match the exception to one of the catch handlers (based on type of item thrown) If a match is found, the code in the catch block executes Only one catch block will be matched, if any Program control resumes after the last catch block If no exception occur in a try block, the catch blocks are skipped A point where an exception occurs is the throw point Keyword throw used to throw an exception to be caught

  7. How? In C++, there is a standard library with pre-built exception classes #include <exception> using std::exception; When a function intends to throw an exception back to the caller (not handled internally), it s good to tell the caller what to expect via a throw list when declaring a function void someFunction throw (DivideByZero, OtherException); This can be used to limit the type of exceptions that a function is allowed to throw

  8. How? void someFunction1() throw(); // empty throw list void someFunction2(); // no throw list The first function can throw no exceptions to the outside The second can throw exceptions of any kind

  9. Simple Example http://www.cs.fsu.edu/~myers/cop3330/examples/exc eptions/except.cpp

  10. Main.cpp #include <iostream> using namespace std; int main() { int cookies, people; double cpp; try { cout << Enter number of people: ; cin >> people; cout << Enter number of cookies: ; cin >> cookies if (cookies == 0) throw people; if (cookies < 0) throw static_cast<double>(people);

  11. Main.cpp cpp = cookies/static_cast<double>(people); cout << cookies << cookies.\n << people << people.\n << You have << cpp << cookies per person.\n ; } catch(int e) { cout << e << people, and no cookies!\nGo buy some cookies!\n ; } catch(double t) { cout << Second catch block type double do we reach it?\n ; } cout << End of program.\n ; return 0; }

  12. Negative Number Example http://www.cs.fsu.edu/~myers/savitch3c++/Ch18/18- 04.cpp

  13. 18-04.cpp #include <iostream> #include <string> using namespace std; class NegativeNumber { public: NegativeNumber() {} NegativeNumber(string m): message(m) {} string getMessage() const ( return message; } private: string message; }; class DivideByZero {};

  14. 18-04.cpp int main() { int pencils, erasers; double ppe; try { cout << How many pencils do you have?\n ; cin >> pencils; if (pencils < 0) throw NegativeNumber( pencils ); cout << How many erasers do you have?\n ; cin >> erasers; if (erasers < 0) throw NegativeNumber( erasers ); if (erasers != 0) ppe = pensils/static_cast<double>(erasers); else throw DivideByZero();

  15. 18-04.cpp cout << Each eraser must last through << ppe << pencils.\n ; } catch(NegativeNumber e) { cout << Cannot have a negative number of << e.getMessage() << endl; } catch(DivideByZero) { cout << Do not make any mistakes.\n ; } cout << End of program.\n ; return 0; }

  16. Safe Divide Example http://www.cs.fsu.edu/~myers/savitch3c++/Ch18/18- 05.cpp

  17. 18-05.cpp #include <iostream> #include <cstdlib> using namespace std; class DivideByZero {}; double safeDevide(int top, int bottom) throw (DivideByZero) { if (bottom == 0) thorw DivideByZero(); return top/static_cast<double>(bottom); }

  18. 18-05.cpp int main() { int numerator, denominator; double quotient; cout << Enter numerator:\n ; cin >> numerator; cout << Enter denominator:\n ; cin >> denominator; try { quotient = safeDivide(numerator, denominator); } catch(DivideByZero) { cout << Error: Division by zero!\n ; << Program aborting.\n ; exit(0); } cout << numerator << / << denominator << = << quotient << endl; return 0; }

Related


More Related Content