Catching exceptions but don't want to cast the type.

U

UJ

I have a try catch where I don't know all of the exceptions that can be
thrown (I'm calling a web service in the try) and what I would ideally like
to do is a catch all but then look at the type of exception that was thrown
and decide what to do there. Because I don't know what all can be thrown I
need to have sort of a generic exception where I can then say - what type is
it ? and then process accordingly. I don't want to do a (Execption ex)
because that will lose some information - or at least I think it will.

I've tried doing catch (object ex) and it won't let me. Object must be
derived from System.Exception.

TIA - Jeff.
 
U

UJ

Nevermind folks. I found out that even if you say (Exception ex) you can
still find out what type it is and go from there.

Thanks anyway.
 
M

Morten Wennevik

Hi Jeff,

You can also catch various exceptions and end with the general exception.

try
{
// risky stuff
}
catch(SpecificException 1)
{
}
catch(SpecificException 2)
{
}
catch(SemiGeneralException)
{
}
catch(Exception e)
{
}

The order needs to be sorted by inheritance as everything that inherits a
certain exception will be caught by that catch block.
 
U

UJ

Thanks everybody for the help. I guess my real question was what do you do
when you don't know what exceptions can be thrown. I assumed that since you
said (Exception ex) that would mean that ex would be type exception. But it
turns out that is not true. ex will be of whatever type it was. So now I can
at least put in the checks that I know will happen and then do the all else
and keep track of what it found so I can add it later.

Thanks again.
 
M

Mehdi

Thanks everybody for the help. I guess my real question was what do you do
when you don't know what exceptions can be thrown. I assumed that since you
said (Exception ex) that would mean that ex would be type exception. But it
turns out that is not true. ex will be of whatever type it was. So now I can
at least put in the checks that I know will happen and then do the all else
and keep track of what it found so I can add it later.

Note that in your particular case, the only exceptions that can AFAIK be
thrown by a web service call are WebException and SoapException. So you it
seems a bit overkill to catch everything and then filter. You could do
something like:

try
{
// Call Web Service Method
}
catch (SoapException ex)
{
// Error occured when processing the web service request on the Web Server
}
catch (WebException (ex)
{
// Network error (host not found, 404...)
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top