[Q] Are Exceptions used that much in practice?

D-Man dsh8290 at rit.edu
Tue Dec 12 23:31:35 EST 2000


I would go for python because it has more features (ie classes) and is much
easier to read/maintain.  As others have stated, Python doesn't enforce
exception catching as Java does, and doesn't even allow you to declare (as part
of the code) what exceptions a funciton might throw.  However, exceptions are
very useful.  For example, here is some C code that I wrote for a course not too
long ago:

==============================

int
main( int argc, char** argv )
{
	FunctionData data ;
	FILE* input_file ;
	float result ; /* the root of the function */
	int i ; /* a loop counter */
	int status ; /* the return value from scanf */

	/* to begin with, register the function to call when the program ends */
	atexit( &exit_func ) ;


	/* check the number of arguments */
	if ( argc != 2 )
	{
		/* print a usage message */
		puts( "Invalid arguments." ) ;
		puts( "Usage:  roots <filename>" ) ;
		exit( EXIT_FAILURE ) ;
	} /* if ( argc != 2 ) */


	/* open the file */
	input_file = fopen( argv[1], "r" ) ;

	/* check for errors */
	if ( errno != 0 )
	{
		/* print an error message */
		perror( "" ) ;
		exit( EXIT_FAILURE ) ;
	} /* if ( errno != 0 ) */


	/* get the endpoints from the file */
	status = fscanf( input_file, "%f %f", &data.endpoints[0], 
			&data.endpoints[1] ) ;

	/* check for errors */
	if ( status != 2 )
	{
		fprintf( stderr, "Missing endpoint.\n" ) ;
		exit( EXIT_FAILURE ) ;
	} /* if ( errno != 0 ) */


	/* get the number of terms in the polynomial */
	status = fscanf( input_file, "%d", &data.func.num ) ;

	/* check for errors */
	if ( status != 1 )
	{
		fprintf( stderr, "Bad file: couldn't read number of terms.\n" );
		exit( EXIT_FAILURE ) ;
	} /* if */


	/* check for validity of input */
	if ( data.func.num < 3 || data.func.num > 10 )
	{
		fprintf( stderr, "The number of terms must be bewteen 3 and " );
		fprintf( stderr, "10, inclusive.\n" ) ;
		exit( EXIT_FAILURE ) ;
	} /* if ( ! 3 < data.func.num < 10 ) */

	polynomial_init( &data.func ) ;

	/* now read the coefficients into the polynomial */
	for( i = 0 ; i < data.func.num ; i++ )
	{
		status = fscanf( input_file, "%f", &data.func.coeffs[i] ) ;

		/* check for error reading file */
		if ( status != 1 )
		{
			fprintf( stderr,
				"There are too few values for coefficients.\n");
			exit( EXIT_FAILURE ) ;
		}
	} /* for */


	/* now read the exponents into the polynomial */
	for( i = 0 ; i < data.func.num ; i++ )
	{
		status = fscanf( input_file, "%d", &data.func.exp[i] ) ;
		/* check for error reading file */
		if ( status != 1 )
		{
			fprintf( stderr,
				"There are too few values for exponents.\n" ) ;
			exit( EXIT_FAILURE ) ;
		} 
	} /* for */


	/* find the root */
	result = bisect( data, EPSILON ) ;

	/* print the information */
	printf( "The given interval is [%4.2f, %4.2f].\n\n", \
			data.endpoints[0], data.endpoints[1] ) ;
	printf( "The given equation is:\n" ) ;
	print_polynomial( stdout, data.func ) ;
	putchar( '\n' ) ;
	printf( "Approximate value of the root is: %8.6f\n", result ) ;

	polynomial_clear( &data.func ) ;

	return EXIT_SUCCESS;
} /* main */

==============================

Since C doesn't have exception handling, I need to clutter the code with if
statements to check for errors after each operation.  If you're not paying
attention to the code, or I hadn't commented it you wouldn't be able to
determine what it should do very easily.  If I write the same funcitonality
(only for the beginning though) using Python and assuming that all functions
will throw an exception if there is an error it would look like this:

==================================
EXIT_SUCCESS = 0 
EXIT_FAILURE = 1

# check the number of arguments
if ( len( sys.argv != 2 ) :
	# print a usage message
	puts( "Invalid arguments." )
	puts( "Usage:  roots <filename>" )
	sys.exit( EXIT_FAILURE )
# end if


try :
	# open the file
	input_file = open( sys.argv[1], "r" )

	# get the endpoints from the file
	# hmm, guess I'm not that familiar with input in python, I'll just leave
the C here
	input_file.fscanf( "%f %f", &endpoints[0], &endpoints[1] )

	# get the number of terms in the polynomial
	input_file.fscanf( "%d", &num ) 

	# check for validity of input
	if ( not ( 3 < num < 10 ) ) :
		print >> sys.stderr, "The number of terms must be bewteen 3 and
10, inclusive."
		sys.exit( EXIT_FAILURE ) ;
	# end if

	# now read the coefficients into the polynomial
	for i in range( num ) :
		coeffs[i] = input_file.fscanf( "%f" )
	# end for

	# rest of processing here
except :
	input_file.close()
	print >> sys.stderr , "There was an error processing the input."

# now the program terminates
==================================

I think you can see how much easier it is to read the flow of execution.  This
program is supposed to get a filename on the commandline then read a polynomial
from the file and find a root of it.

Of course, most of this would be written as support functions that would be
executed as part of the ctor (__init__ function) in a class called Polynomial. 
I choose not to do a complete rewrite here, and also gives a closer comparison
to the original C.


In answer to your question, exceptions are very useful and convenient and
improve the readiabilty of the programs/functions greatly.  They also provide an
easy way to terminate a function/program if some bad error condition occurs. 
(ie, if no one catches an exception the program will terminate).  I would pick a
language that has exceptions over a language that doesn't any day.

I also feel that I should point out a flaw in my example:  it seems to indicate
that you can't make useful error messges using exceptions.  That is not so, I
simply didn't put the time in to do so.  When you catch exceptions, you can
specify the types of exceptions to catch.  Each type of exception can have it's
own 'except' block that can produce different results..

HTH

-D


On Tue, 12 Dec 2000 19:46:27 Jerome Mrozak wrote:
 | I believe I've been misunderstood.  The problem is not "can I write code
 | without handling exceptions" but rather "are exceptions used
 | voluntarily, rather than by compulsion".
 | 
 | An example of compulsion is java.lang.Integer.parseInt(), which throws a
 | NumberFormatException you *must* deal with or the program won't
 | compile.  I'm aware of examples of Python such as (faking it here):
 | 
 | while 1:
 |   try:
 |     input = inputFileObject.readline()
 |   catch EOF:
 |     break
 |   else:
 |     process(input)
 | 
 | The point of the question is this -- is code like this sample a way of
 | exercising the try-catch, or is this an example of something I end up
 | doing all of the time because it is so much easier than the alternative?
 | 
 | Other posters to this question provided a fair sampling of examples.
 | 
 | Some, I'm disappointed to say, were, shall we say, not so supportive.  
 | 
 | The long-range goal of my question is to determine for my satisfaction
 | whether it is worth while for me to spend my limited time pursuing
 | Python as a compliment to (whatever other skills I might have) or to go
 | with the apparently much greater flow and use those resources on Perl. 
 | The 'exception' thing could be a determiner, esp. with nothing similar
 | in Perl, but only if I can use it in a *positive* way instead of just to
 | test a return value.  Heck, Perl has 'die' for that kind of testing.
 | 
 | Thanks for your concern anyways.
 | 
 | Jerome.
 | 





More information about the Python-list mailing list