[Mono-list] Exceptions and error codes.

Thong (Tum) Nguyen tum@veridicus.com
Wed, 26 Mar 2003 04:09:21 +1200


Hi Miguel,

There are definitely examples where exceptions can slow down your code.
The thing is, how often would those cases appear in the real world, and
when they do appear would they be a hotspot?

WRT your example...

If you're expecting many of the lines to contain non-integers then it
would make sense to seek an alternative method because you're then using
exceptions to notify you of a situation that you *normally* expect.  The
problem isn't that Int32.Parse throws exceptions, it's because you're
using Int32.Parse in a way that wasn't intended.  Int32.Parse isn't
designed for testing whether something is an int or not.  Int32.Parse
expects to be given valid input most of the time and fails (with an
exception) when you (or the user) "accidentally" give it invalid input.
In your example, it looks like a non-int line isn't invalid input but
simply alternate input.

Since the loop appears to be a meaty part of the program my solution
would be to use a tokenizer.

^Tum

> -----Original Message-----
> From: mono-list-admin@lists.ximian.com [mailto:mono-list-
> admin@lists.ximian.com] On Behalf Of Miguel de Icaza
> Sent: Monday, 24 March 2003 3:43 p.m.
> To: tum@veridicus.com
> Cc: mono-list@lists.ximian.com
> Subject: Re: [Mono-list] Exceptions and error codes.
> 
> Hello,
> 
>     You do raise interesting points.
> 
>     The problem with exceptions is that throwing and catching an
> exception is an expensive operation.  Using an exception as a
mechanism
> to return a failure error, when failure is likely to happen is
> inefficient.
> 
>     Contrast `likely to happen error' with `exceptional condition:
> internal error, or unlikely error to happen'.
> 
>     Lets consider a sample: a program that uses Int32.Parse to detect
> whether an integer is available, or maybe a string command exists, and
> we are parsing, say, a million records:
> 
> 	for (i = 0; i < one_million; i++){
> 		string line = readline ();
> 		try {
> 			v = Int32.Parse (line);
> 			handle_numberic_argument ();
> 		} catch {
> 			ParseCommand (line);
> 		}
> 	}
> 
>     This is so bad, that you probably want to rewrite the code to
> pro-actively avoid parsing things that are known not to be integers.
> 
>     It is easy to turn an error-code API into an exception-throwing
API
> with no performance loss.   The opposite is not possible.
> 
> Miguel
> _______________________________________________
> Mono-list maillist  -  Mono-list@lists.ximian.com
> http://lists.ximian.com/mailman/listinfo/mono-list
> 
> ---
> Incoming mail is certified Virus Free.
> Checked by AVG anti-virus system (http://www.grisoft.com).
> Version: 6.0.461 / Virus Database: 260 - Release Date: 10/03/2003
> 

---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.461 / Virus Database: 260 - Release Date: 10/03/2003