-
Exceptions
(yes, another question from me)
Code:
try
{
...
}
catch(Exception e)
{
...
}
I noticed that not all exceptions are derived from the Exception class, and so I was wandering: Would the code above execute the catch code regardless of which sepcific type of exception was thrown? I'd like to be able to give the user some information about what type of exception occured, but if the above is not possible, do I have to specify and argument for the catch block? And then am I able to handle multiple types of exceptions with multiple catch blocks?
Thanks,
Sean.
-
Contrary to C++ where you can just catch(...) and throw anything you like in .NET you can only throw Exceptions( and derived classes ) and you can only catch Exceptions and derived classes.
You can specialize your catch blocks. For example:
try
{
// something
}
catch( NotSupportedException nse )
{
// something threw a NotSupportedException
}
catch( ArgumentNullException ane )
{
// something threw an ArgumentNullException
}
catch( Exception e )
{
// something threw anything but NotSupported or ArgumentNull Exceptions
}
You can derive your own exception classes from Exception ( better yet there are already two subclasses you should derive from, look it up in the MSDN, I don't remember the names ) and use it just like the derived exception classes in the .NET Framework.
public class FooException : Exception
{
}
try
{
throw new FooException;
}
catch( FooException foo )
{
// will be caught
}
try
{
throw new FooException;
}
catch( Exception e )
{
// will be caught
}
-
Sean,
Why don't you use the Message property it provides a short description of the exception:
Code:
try
{
}
catch(DivideByZeroException e)
{
Console.WriteLine(e.Message);
}
-
Oh - I know about the Message property - thanks. What I'm asking is if I can use
and have that code executed in the event that ANY exception occurs. Will this happen? I'm afraid I found nvoight response a little confusing.
The reason I'm asking is because during testing I may not simulate conditions that a certain user might use that would generate a certain exception. All the common exceptions will be handled specifically, but I just want a kind of catch-all block. Would the above work?
edit: Grr.... I just realized that a "finally" block would do exactly what I wanted... Well I'll leave the rest here to explain what I was asking and for anyone else who's searching the forums. Thanks for the help guys!
-
Indeed, a catch( Exception e ) will catch anything that is thrown, just like catch( ... ) in C++ does :D