Throwing exceptions created with reflection

  • Thread starter Thread starter kaloianm
  • Start date Start date
K

kaloianm

Hi,

Does someone know whether it is a bad practice to create exception
objects through reflection and throw them? I want to use this in order
to dynamically convert from an integer errorCode to an exception (via a
map errorCode -> typeof( Exception))?

Assembly excAssembly = _exceptionType.Assembly;
Object [] args = new Object [ 1] { _errorCode };
Exception e =
(Exception)excAssembly.CreateInstance( _exceptionType.FullName,

false,

BindingFlags.CreateInstance,

null,

args,

null,

null);
throw (e);

Thanks in advance,
Kaloian.
 
Kaloian,

Well, what are your concerns? I mean, when you throw the exception, you
just throw it. Granted, the idea of mapping an integer code to an exception
is a little odd to me, since I think that the integer code is enough (and
you don't necessarily have to throw an exception).

I think there is a difference between an error code and an exception,
but in the end, it's up to you.

Hope this helps.
 
That's very bad code practice.
Exceptions are too expensive to use for processing, don't do that.

If your entire objective is to raise an Exception, then how can it be bad
practice?

What are you up to?
 
John said:
That's very bad code practice.
Exceptions are too expensive to use for processing, don't do that.

What exactly do you mean by "for processing"? Whether exceptions are
too expensive depends on how often the relevant situation will occur,
and what the performance demands are.

Just how expensive do you believe exceptions are?

Without trying it (or following the link yet) how many exceptions do
you think can be thrown in a second? You may well be surprised.

See http://www.pobox.com/~skeet/csharp/exceptions.html for my take on
the issue.
 
Back
Top