Camilo Martin Camilo Martin - 5 months ago 15
Vb.net Question

Why can't I write just a try with no catch or finally?

Sometimes I do this and I've seen others doing it too:

VB:



Try
DontWannaCatchIt()
Catch
End Try


C#:



try
{
DontWannaCatchIt();
}
catch {}


I know I should catch every important exception that I'm expecting and do something about it, but sometimes it's not important to - or am I doing something wrong?

Is this usage of the
try
block incorrect, and the requirement of at least one
catch
or
finally
block an indication of it?

Update:



Now I understand the reason for this, and it's that I should at least comment on the empty catch block so others understand why it's empty. I should also catch only the exceptions I'm expecting.

Luckily for me I'm coding in VB so I can write it in just one catch:

Catch ex As Exception When TypeOf ex Is IOException _
OrElse TypeOf ex Is ArgumentException _
OrElse TypeOf ex Is NotSupportedException _
OrElse TypeOf ex Is SecurityException _
OrElse TypeOf ex Is UnauthorizedAccessException
'I don't actually care.
End Try

Answer

If you don't want to catch it, why are you using try in the first place?

A try statement means that you believe something can go wrong, and the catch says that you can adequately handle that which you catch.

So in your estimation:

try
{
    //Something that can go wrong
}
catch
{
    //An empty catch means I can handle whatever goes wrong. If a meteorite hits the
    //datacenter, I can handle it.
}

That catch swallows any exceptions that happen. Are you that confident in your code that you can handle anything that goes wrong gracefully?

The best thing to do (for both yours and your maintenance programmer's sanity) is to explicitly state that which you can handle gracefully:

try
{
    //Something that could throw MeteoriteHitDatacenterException
}
catch (MeteoriteHitDatacenterException ex)
{
    //Please log when you're just catching something. Especially if the catch statement has side effects. Trust me.
    ErrorLog.Log(ex, "Just logging so that I have something to check later on if this happens.")

}
Comments