Choosing nothing over exceptions

Given the powerful features of a try-catch block, it is sometimes tempting to handle all negative scenarios with Exception types. In practice, we want to be very clear about what is truly an exception and what is a normal negative case.

We can turn to the match function as an example. The match function from the Base package can be used to match a regular expression against a string. If there is a match, then it returns a RegexMatch object, which contains the captured results. Otherwise, it returns nothing. The following example illustrates this effect:

The first match function call returned a RegexMatch object because it found that google.com ends with .com. The second call could not find any match and so it returned nothing.

By design, the match function does not throw any exception. Why not? One reason for this is that the function is frequently used for checking whether a string contains another string and then the program decides what to do either way. Doing that would require a simple if statement; for instance, refer to the following code:

url = "http://google.com"
if match(r".com$", url) !== nothing
# do something about .com sites
elseif match(r".org$", url) !== nothing
# do something about .org sites
else
# do something different
end

If it were to throw an exception instead, then our code would have to look different, as follows:

url = "http://google.com"
try
match(r".com$", url)
# do something about .com sites
catch ex1
try
match(r".org$", url)
# do something about .org sites
catch ex2
# do something different
end
end

As you can see, the code can get very ugly very quickly using a try-catch block.

When designing a programming interface, we should always think about whether an exception is truly an exception or whether it could be just a negative status. In the case of the match function, a negative case is effectively represented by nothing.

In this section, we learned where to place try-catch blocks in our code. Now we should be able to properly catch exceptions and examine the stack frames.

We have come to understand better how performance may be impacted by the exception-handling code. Based on our understanding, we should be able to design and develop more robust software.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.227.114.125