Ignoring exceptions

  • Thread starter Thread starter Ken Foskey
  • Start date Start date
K

Ken Foskey

Is this the 'correct' way to ignore exceptions?

public void Close()
{
try
{
MethodThatMayThrowException();
}
finally
{
FlagClosed = true;
}
}
 
Ken said:
Is this the 'correct' way to ignore exceptions?

public void Close()
{
try
{
MethodThatMayThrowException();
}
finally
{
FlagClosed = true;
}
}

I don't think so.

The code calling your close will still get the
exception.

public void Close()
{
try
{
MethodThatMayThrowException();
}
catch(FoobarException)
{
// don't want to do anything about this exception
}
finally
{
FlagClosed = true;
}
}

is ignoring FoobarException.

Note that in many cases ignoring an exception is not good !

Arne
 
Is this the 'correct' way to ignore exceptions?

public void Close()
{
        try
        {
                MethodThatMayThrowException();
        }
        finally
        {
                FlagClosed = true;
        }

No, because "finally" does not swallow the exception. It just ensures
that code inside will run even if exception happens while executing
whatever is inside "try".

To ignore a specific exception, you just use an empty catch block:

try { ... } catch (IOException) {}

Ignoring all exceptions is generally not something you ever want to
do, except when you're developing for SharePoint *sigh*. In which case
you just catch anything derived from Exception.

Of course, even ignoring a very specific exception is something that
raises an eyebrow. Typically, you'd at least have some logic there
depending on whether it happens or not, and not an empty catch,
 

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

Back
Top