[Mono-list] Exceptions and error codes.

Eran Sandler Eran.Sandler@smarteam.com
Mon, 24 Mar 2003 09:55:20 +0200


As a rule of thumb consider the following:

Exceptions should be used when UNEXPECTED errors might occur and you
don't want to blow up the whole application. When you do know what a
certain code should return, use it.

That is how I usually try to do things.

When I write API I sometimes have two functions that do the same thing
but one throws an exception and the other return some kind of a result.

For example:

public class SampleAPI
{
	public string GetName();
	public string VerifyGetName();
}

GetName returns null if the name cannot be retrieved. VerifyGetName
calls GetName and if a Null return it throws an exception.

The person using this API can than decide if he wants to deal with the
error alone or simply call Verify that will throw an exception for him.

Eran


-----Original Message-----
From: Miguel de Icaza [mailto:miguel@ximian.com]=20
Sent: Monday, March 24, 2003 5:43 AM
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'. =20

    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 =3D 0; i < one_million; i++){
		string line =3D readline ();
		try {
			v =3D 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