It seems that "throw new Expcetion(...)" (in C#) is not a good
practice because the exception is too generic to catch without ignoring
some low level exceptions such as OutOfMemoryException and
StackOverflowException. For me, I cannot figure out any advantage to
throw Exception directly except forcing the client to use "catch
(Exception ex)" or to prevent this exception from throwing by checking
some conditions.
For example, System.Drawing.Graphics.FromImage(Image image) will
throw Exception if the specified image is an image of indexed pixels. I
know I can check (image.PixelFormat & PixelFormat.Indexed) before
calling FromImage() to prevent this problem. However, in other cases,
there may not be any condition I can check in advance before the
Exception is thrown.
Hence, here are my questions: Is "throw new Exception(...)" a good
practice? If not, why do Microsoft programmers implement it in this
way?
Patrick
If you want to re-throw an existing exception, just throw. The original
exception
will then be able to be traced.
See http://www.codeproject.net and search for the several recent
articles
on best exception handling practices.
-- Tom
"Patrick" <ying...@gmail.com> wrote in message
news:1110735318.7...@l41g2000cwc.googlegroups.com...
Thank for the reply. However, I am asking "Is it good to throw
System.Exception instead of other types derived from
System.Exception?". Sorry for the confusion.
Patrick
"Patrick" <ying...@gmail.com> wrote in message
news:1110738555.5...@z14g2000cwz.googlegroups.com...
"Patrick" <ying...@gmail.com> wrote in message
news:1110735318.7...@l41g2000cwc.googlegroups.com...
catch (Exception e)
{
throw new Exception ("My grain of salt", e) ;
}
you add your own information and keep all the stack of the lower level
exceptions. So you can just enrich the lower level exception with
information pertaining to the exact condition under which it occurs in your
code.
/LM
Unless there's some reason not to throw an exception of the same type
(perhaps some operations are security sensitive) I find myself doing this...
catch(Exception ex)
{
// if cannot recover then...
throw CloneException("Add some context info.",ex);
}
The method CloneException creates a new exception object of the same type as
the original (if possible), and it wraps the original exception in the
InnerException field of the new exception.
If the code is creating and throwing a brand new exception then I generally
try to use an existing exception class, such as ArgumentOutOfRangeException,
etc.
IMO this is an area that still needs lots of thought, research, and work.
"Patrick" <ying...@gmail.com> wrote in message
news:1110735318.7...@l41g2000cwc.googlegroups.com...