How to Deal With Errors in C++

By eHow Computers Editor

Rate: (4 Ratings)

As a programmer, it's your job to produce robust systems that run smoothly at all times. You don't have to write functions that check flags and return cryptic error codes. Program recovery from a bad situation can be smooth because of a mechanism called C++ Exception Handling. Objects called Exceptions can be "thrown" from the error site and "caught" by an Exception Handler, giving you a chance to set things right.

Instructions

Difficulty: Challenging

Things You’ll Need:

  • C++ Development Environment
Step1
Create an exception class for each base class in your design using a C++ development environment. All can share a common structure. For a File base class create a FileException exception class, for a GameEntity base class create a GameEntityException exception class. Get the pattern?
Step2
Place the exception class inside the public area of the base class. The exception class has to be visible as it will be called by the handler.
Step3
Give each exception class a constructor that accepts an input string. The input string will contain the error message that will be displayed when the exception object gets caught by the handler.
Step4
Create a handler function for each exception class you have designed. Each handler function is an overloaded "catch" function differing in the type of input argument. The first line of the two handlers would look like, "catch(File::FileException* e) {…" and "catch(GameEntity::GameEntityException* e) {…". Place these exception handler functions right underneath 'main.'
Step5
Inundate your programming space with "throw" statements. Put them in two major areas. Insert "throw" statements where you see potential for trouble, "if (/*divide by zero*/) {throw Math::MathException("division by zero");}. Declare a 'throw' statement on the right of a function or class that calls exceptions, "void Divide(/*parameters*/) throw (Math::MathException) {…".
Step6
Insert your execution code inside "main," within "try" braces. The C++ exception handling mechanism has a try, throw and catch structure. Not only does this make programs extremely robust but it is pleasant to read.

Tips & Warnings

  • With exception handling, errors are handled in parallel with the normal flow of execution.

Post a Comment

POST A COMMENT

Request a New How-To Article

Looking for more How To information? Chances are there’s an eHow member who knows how to do what you’re looking to do. Submit an article request now!

eHow Article: How to Deal With Errors in C++

eHow Computers Editor

eHow Computers Editor

Category: Computers

Articles: See my other articles

Related Ads