Programming Forums
User Name Password Register
 

RSS Feed
FORUM INDEX | TODAY'S POSTS | UNANSWERED THREADS | ADVANCED SEARCH

Reply
 
Thread Tools Display Modes
Old Nov 30th, 2005, 8:42 PM   #1
Jessehk
The Oblivious One
 
Jessehk's Avatar
 
Join Date: May 2005
Location: Ontario, Canada
Posts: 644
Rep Power: 4 Jessehk is on a distinguished road
Starting to use exceptions

The book I am reading just spent a about 10 pages with exceptions (relative to the other material, not much), and I just wanted to clarify things. I now know about the standard exception class, and how to use them. I wanted to get clarification on their proper use. Now, I know they are mostly used for input errors, memory allocation errors, bounds errors, etc.

However, what their use to solve a simple problem also be considered "acceptable"?

eg: using exceptions to check login password

password.h

#ifndef PASSWORD_H_
#define PASSWORD_H_

//password.h -- Password class declaration
#include <string>

class Password
{
	private:
		std::string pass;
	public:
		Password(std::string set)
			: pass(set) {}
		bool check(std::string atm) {return atm == pass;}
};

class BadPassword
{
	public:
		BadPassword() {}
		void message() {std::cout << "Incorrect password" << std::endl;}
};

#endif

password.cpp

//password.cpp -- testing the Password class
#include <iostream>
#include "password.h"

int main()
{
	Password pass1("password");

	std::string attempt;
	while(1)
	{
		try
		{
			std::cout << "Enter password: ";
			std::getline(std::cin, attempt);
			if(pass1.check(attempt))
				break;
			else
				throw BadPassword();
			
		}
		
		catch(BadPassword &bp)
		{
			bp.message();
		}
			
	}

	std::cout << "Welcome!" << std::endl;
}
__________________
Dr. Zoidberg: [ecstatic] I'm going to a movie... with FRIENDS!
Jessehk is offline   Reply With Quote
Old Nov 30th, 2005, 9:01 PM   #2
jayme
Professional Programmer
 
jayme's Avatar
 
Join Date: Nov 2005
Location: Canada
Posts: 495
Rep Power: 0 jayme is an unknown quantity at this point
Send a message via MSN to jayme
haha, what a perfect time to post this.. that code was the exact thing i needed for me to understand the classes! Time to start working on my experience system thanks
__________________

Quote:
Originally Posted by Mohamed Jihad
Durka durka!
Due to incorrect calculations during the middle ages, our calendar actually begins a few years after Jesus' birth. Thus the real 6/6/6 happened a few years back. The world already ended and you missed it.

Download Code::Blocks now!
jayme is offline   Reply With Quote
Old Nov 30th, 2005, 9:36 PM   #3
Jessehk
The Oblivious One
 
Jessehk's Avatar
 
Join Date: May 2005
Location: Ontario, Canada
Posts: 644
Rep Power: 4 Jessehk is on a distinguished road
EDIT: Sorry for the awful typos. I wish the edit button did not dissapear...
__________________
Dr. Zoidberg: [ecstatic] I'm going to a movie... with FRIENDS!
Jessehk is offline   Reply With Quote
Old Dec 1st, 2005, 3:06 AM   #4
grumpy
Programming Guru
 
grumpy's Avatar
 
Join Date: Jun 2005
Location: Adelaide, South Australia
Posts: 1,223
Rep Power: 5 grumpy is on a distinguished road
Quote:
Originally Posted by Jessehk
The book I am reading just spent a about 10 pages with exceptions (relative to the other material, not much), and I just wanted to clarify things. I now know about the standard exception class, and how to use them. I wanted to get clarification on their proper use. Now, I know they are mostly used for input errors, memory allocation errors, bounds errors, etc.
More generally, exceptions are used to report errors that, if ignored, can cause irrecoverable errors in the program. By throwing an exception in such cases, it is guaranteed that the error will either be handled (and presumably recovered from) or the program will exit.

Memory allocation errors are a good example: in most cases, it is not possible for a program to recover if an error occurs when allocating memory. However, if it is possible in a particular program to recover from a memory allocation problem, then all that program needs to do is catch the relevant exception. This is one reason that operator new, by default, throws exceptions if an error occurs.

Input errors is one example where it it not necessarily a good idea to throw an exception. For example, one of my pet peeves in Java is that an exception is thrown on end of file by some operations: this complicates things enormously when a program is doing something along the lines of (in pseudo code)
    if (read_data_from_file() != EOF)
           process_data();
which becomes;
try
{
    read_data_from_file();
    process_data();
}
catch (eof_occurred)
{
}
which is a more complicated way of doing the same thing.
Quote:
Originally Posted by Jessehk
However, what their use to solve a simple problem also be considered "acceptable"?
Generally, it is best to use the way of reporting errors that is best suited to the scenario at hand. If an error can be recovered from at the point where it is detected, throwing an exception is not a good idea. If an error can NOT be recovered from at the point where it is detected, throwing an exception is a good idea if chaos would occur if recovery actions did not happen. If an error can NOT be recovered from at the point where it is detected, throwing an exception is NOT a good idea if the program can continue to execute happily even if recovery actions do not occur.

A clue that throwing exceptions are a bad idea is if you find yourself continually writing throw/catch blocks concerned with little more than ignoring the error. Another clue that throwing exceptions is a bad idea is if MANY function has to include try/catch blocks: as a rough rule, most functions should happily let an exception pass through if nothing can be done about it.

A clue that throwing exceptions is a good idea is if you find yourself having to track down instances where you have forgotten to check a return status from a function that reported an error.

I would suggest that catching an exception within the function that threw it is NOT a good idea, although it is not necessarily "wrong". Would it be a better idea to check the return value from password.check() and print an error message if a failure has occurred? As a rough rule, the code that is easiest to read is often best. And I would suggest an approach without exceptions would be simpler.
grumpy is offline   Reply With Quote
Old Dec 3rd, 2005, 4:33 AM   #5
lectricpharaoh
Caffeinated Neural Net
 
lectricpharaoh's Avatar
 
Join Date: Jun 2005
Location: Dry west coast of Canada
Posts: 1,032
Rep Power: 5 lectricpharaoh will become famous soon enough
In addition to what grumpy said, you should bear in mind exceptions are much more expensive (in performance terms) than the simple checking of a return value. For most function calls, you have three exit conditions: 1) complete success, 2) partial success, and 3) failure.

For example, let's say I try to read 100 records from a file. If the file is opened successfully, has 100 records, and I make the read call correctly, it's a safe assumption the operation will be a success (though 'acts of God' like hardware failure, etc can still muck with that). Now let's say the file only has 70 records- this would be partial success. The call didn't error out, but I didn't get all that I wanted. Third would be a failure, often due to unsuccessfully opening the file (though in well-written code, a program won't try to use such a file), or some other task locking or altering the file, etc. If you check functions like fread(), they will return EOF on error, or the number of items read on success. You can easily use this is an if() construct to check for errors, and your code will be cleaner and more efficient than using an exception-handling mechanism.

Likewise, for your password code, it could either be a plain function that returned, say, the password as a C-style string on success, and NULL on failure, or it could be a class that constructed a password object, and then had some test for success, much like the <iostream> classes do (istream::fail() and the like).
__________________
And once again, Probability proves itself willing to sneak into a back alley and service Drama as would a copper-piece harlot.
- Vaarsuvius, Order of the Stick
lectricpharaoh is offline   Reply With Quote
Reply

Bookmarks

« Previous Thread in Forum | Next Thread in Forum »

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump




DaniWeb IT Discussion Community
All times are GMT -5. The time now is 7:57 PM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC