Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do try blocks need a catch

I have this code :

try 
{
    result.FirstName = nodes[myIdx]
        .Attributes["ows_FirstName"].Value;
} 
catch { }

Now I don't know prior to invoking this call if the attribute I am looking for exists (Good ol sharepoint).

As a result the only linear way I can write the code I am looking to create is as such.

try 
{
    result.FirstName = nodes[myIdx]
        .Attributes["ows_FirstName"]
        .Value;
} 
catch { }

try 
{
    result.LastName = nodes[myIdx]
        .Attributes["ows_LastName"]
        .Value;
} 
catch { }

Now I have no use for the catch section of this code and end up with a huge amount of lines that are completely redundant.

Why couldn't I just do

try 
{
    result.FirstName = nodes[myIdx]
        .Attributes["ows_FirstName"]
        .Value;
}

So why are we explicitly forced to declare a catch block even when it isn't handled? I'm sure there is a good reason but can't work it out.

I know the importance of exception handling, but here is simply nothing exceptional about the exception and nothing I can do (nor need to do) to fix the behavior.

like image 464
Maxim Gershkovich Avatar asked Mar 15 '12 02:03

Maxim Gershkovich


1 Answers

They are not redundant - they have a specific purpose. By default the lack of a catch block will re-throw the exception to the calling method. An empty catch block essentially "swallows" the exception and lets the program continue, oblivious to whether or not an exception was thrown; generally a bad practice.

there is simply nothing exceptional about the exception

it may be true that one type of exception may not be "exceptional" in this case, but that's not the only exception that can occur. You should handle that exception and deal with any others appropriately.

For example -

What if nodes is null? What if myIdx is outside the bounds of the nodes array? Either of these conditions would be exceptional and you should either handle them specifically or let the calling program handle them and act appropriately.

[there's] nothing I can do (or need to do) to fix the behaviour

You may not be able to fix it, but you may need to be aware of it. How does the program behave differently in that case? Log a message? Raise a warning? Set a default value? Do nothing may be an appropriate answer, but very likely not an appropriate response to any possible exception.

like image 196
D Stanley Avatar answered Sep 22 '22 14:09

D Stanley