Earlier today, I saw two different StackOverflow questions that basically looked like this:
Why does this not work? 
    try:
        [broken code]
    except:
        print('[-] exception occurred')
Unless someone can read minds or gets lucky or puts a whole lot more work into your question than you have any right to expect, the only answer anyone can give is "because an exception occurred", because your code goes out of its way to make it impossible for you to tell us what exception occurred and why.

This is exactly why you almost never want to handle exceptions with a bare except clause.

So, how do you want to handle exceptions?

If there's a specific exception you want to deal with, handle that

On both posts, someone suggested replacing the except: with except Exception:. But this doesn't really help anything.

OK, yes, it means that you'll no longer catch things like KeyboardInterrupt, which is nice, but it's still not going to help you tell what actually went wrong.

For example, one of the users' broken code was trying to create a socket, but he had a simple typo. Presumably he wanted to handle socket errors in some way, but because he used a bare except, the NameError raised by the typo looked exactly like a socket error. Handling Exception instead of everything wouldn't help that at all; socket.error and NameError are both subclasses of Exception. What you want to do here is handle socket.error.

    try:
        sock = socket(AF_INET, SOCK_STEAM)
    except socket.error:
        print('[-] exception occurred')

This way,  you'll get a traceback telling you there's a NameError on SOCK_STEAM, which is pretty easy to debug.

Sometimes, Exception is the right thing to handle (especially if you want to catch all unexpected exceptions at the very top of your program to log or display them in some way), but usually not.

Almost always use an as clause

Even just handling any Exception would still have allowed the user to debug his problem, if he hadn't thrown away all the information:
    try:
        sock = socket(AF_INET, SOCK_STEAM)
    except Exception as e:
        print('[-] exception occurred: {!r}'.format(e))
This doesn't give you a full traceback, or exit the program, but at least it lets you see NameError("name 'SOCK_STEAM' is not defined"), which is enough to debug the problem.

(If you really need to handle absolutely everything, even things like KeyboardInterrupt that aren't subclasses of Exception, how do you do that? You can't use an as clause with a bare except. But in recent Python—which includes 2.6 and 2.7, not just 3.x—"except BaseException:" does the same thing as "except:", so you write "except BaseException as e:". In earlier versions, you have to call sys.exc_info() to recover the exception.)

The one exception to this is in cases where there's only one thing that could go wrong, and the details of how it went wrong are irrelevant. That isn't actually true in this case—you'd like the log to tell you whether the socket failed because you're out of resources, or don't have permissions, or whatever, not just that it failed. But here are some examples where it's perfectly fine:

    try:
        import xml.etree.cElementTree as ET
    except ImportError:
        import xml.etree.ElemnetTree as ET

    try:
        return main[key]
    except KeyError:
        return backup[key]
(The second one could be handled better by a ChainMap, but let's ignore that; if you do want to do it with try/except, there's no reason to care about the information in the KeyError.)

If you can't handle the exception in some useful way, don't handle it

In the socket example, there's no point handling the error and just continuing on. The very next line of code is almost certainly going to be calling sock.bind or sock.connect, which will just raise a NameError anyway. If the socket creation fails, the whole function has presumably failed, so let the exception propagate back to the caller.

In general, it's your high-level functions that can do something useful with errors, not your mid-level functions (except maybe to reraise them with more context).

A start_server function had better either start the server, or report that it failed to do so in some way; it shouldn't return successfully with the server not running. And the obvious way to report that failure is to raise an exception. So, just let that socket call raise right through start_server.

At a higher level, you're going to have a daemon script or a GUI app or something else. That something else may want to wait 10 seconds and try again, or sys.exit(17), or popup up an error message and re-enable the "Start" button, or whatever. That higher-level function is where you want to handle the exception.

That may mean don't handle it at all

In fact, in many cases—especially early in development—the right place to handle an exception is nowhere at all. Just let the program exit and print a complete traceback that tells you (or, if not you, the people trying to help you on StackOverflow) exactly what you did wrong and where.

You might object that this is a bad end-user experience, but surely printing "[-] exception occurred" and then exiting (or printing out an endless stream of such messages and doing nothing useful) is just as bad of an end-user experience.

Once you have something working, it's often worth wrapping a top-level except Exception as e: at the top level to handle anything that escaped your design, because you want your server to log useful information somewhere and return an appropriate exit code, or you want to display the error in a window with instructions to submit a bug report instead of dumping it to the (possibly-non-existent) console. But until you've got things working at least far enough to do that, it's way too early to be catching everything anywhere.

Sidebar on other languages

Pretty much everything above applies to other languages that use exceptions, not just Python. But there's one more issue that comes up in a few languages, like C++, where you're often using a whole bunch of functions written for C that use status codes instead of exceptions.

In those cases, never call those C functions directly from your mid-level code. Instead, write code that wraps those calls up to raise exceptions when they fail, then use those functions from your mid-level code. (This is especially important if you're using RAII to manage resources, as you really should be in C++.)

This gives you a very simple rule of thumb: Your bottom-level code throws exceptions, your mid-level code just lets exceptions pass through, and your top-level code catches exceptions. That's not universally true, but it's true often enough to be a handy guide.
2

View comments

It's been more than a decade since Typical Programmer Greg Jorgensen taught the word about Abject-Oriented Programming.

Much of what he said still applies, but other things have changed. Languages in the Abject-Oriented space have been borrowing ideas from another paradigm entirely—and then everyone realized that languages like Python, Ruby, and JavaScript had been doing it for years and just hadn't noticed (because these languages do not require you to declare what you're doing, or even to know what you're doing). Meanwhile, new hybrid languages borrow freely from both paradigms.

This other paradigm—which is actually older, but was largely constrained to university basements until recent years—is called Functional Addiction.

A Functional Addict is someone who regularly gets higher-order—sometimes they may even exhibit dependent types—but still manages to retain a job.

Retaining a job is of course the goal of all programming. This is why some of these new hybrid languages, like Rust, check all borrowing, from both paradigms, so extensively that you can make regular progress for months without ever successfully compiling your code, and your managers will appreciate that progress. After all, once it does compile, it will definitely work.

Closures

It's long been known that Closures are dual to Encapsulation.

As Abject-Oriented Programming explained, Encapsulation involves making all of your variables public, and ideally global, to let the rest of the code decide what should and shouldn't be private.

Closures, by contrast, are a way of referring to variables from outer scopes. And there is no scope more outer than global.

Immutability

One of the reasons Functional Addiction has become popular in recent years is that to truly take advantage of multi-core systems, you need immutable data, sometimes also called persistent data.

Instead of mutating a function to fix a bug, you should always make a new copy of that function. For example:

function getCustName(custID)
{
    custRec = readFromDB("customer", custID);
    fullname = custRec[1] + ' ' + custRec[2];
    return fullname;
}

When you discover that you actually wanted fields 2 and 3 rather than 1 and 2, it might be tempting to mutate the state of this function. But doing so is dangerous. The right answer is to make a copy, and then try to remember to use the copy instead of the original:

function getCustName(custID)
{
    custRec = readFromDB("customer", custID);
    fullname = custRec[1] + ' ' + custRec[2];
    return fullname;
}

function getCustName2(custID)
{
    custRec = readFromDB("customer", custID);
    fullname = custRec[2] + ' ' + custRec[3];
    return fullname;
}

This means anyone still using the original function can continue to reference the old code, but as soon as it's no longer needed, it will be automatically garbage collected. (Automatic garbage collection isn't free, but it can be outsourced cheaply.)

Higher-Order Functions

In traditional Abject-Oriented Programming, you are required to give each function a name. But over time, the name of the function may drift away from what it actually does, making it as misleading as comments. Experience has shown that people will only keep once copy of their information up to date, and the CHANGES.TXT file is the right place for that.

Higher-Order Functions can solve this problem:

function []Functions = [
    lambda(custID) {
        custRec = readFromDB("customer", custID);
        fullname = custRec[1] + ' ' + custRec[2];
        return fullname;
    },
    lambda(custID) {
        custRec = readFromDB("customer", custID);
        fullname = custRec[2] + ' ' + custRec[3];
        return fullname;
    },
]

Now you can refer to this functions by order, so there's no need for names.

Parametric Polymorphism

Traditional languages offer Abject-Oriented Polymorphism and Ad-Hoc Polymorphism (also known as Overloading), but better languages also offer Parametric Polymorphism.

The key to Parametric Polymorphism is that the type of the output can be determined from the type of the inputs via Algebra. For example:

function getCustData(custId, x)
{
    if (x == int(x)) {
        custRec = readFromDB("customer", custId);
        fullname = custRec[1] + ' ' + custRec[2];
        return int(fullname);
    } else if (x.real == 0) {
        custRec = readFromDB("customer", custId);
        fullname = custRec[1] + ' ' + custRec[2];
        return double(fullname);
    } else {
        custRec = readFromDB("customer", custId);
        fullname = custRec[1] + ' ' + custRec[2];
        return complex(fullname);
    }
}

Notice that we've called the variable x. This is how you know you're using Algebraic Data Types. The names y, z, and sometimes w are also Algebraic.

Type Inference

Languages that enable Functional Addiction often feature Type Inference. This means that the compiler can infer your typing without you having to be explicit:


function getCustName(custID)
{
    // WARNING: Make sure the DB is locked here or
    custRec = readFromDB("customer", custID);
    fullname = custRec[1] + ' ' + custRec[2];
    return fullname;
}

We didn't specify what will happen if the DB is not locked. And that's fine, because the compiler will figure it out and insert code that corrupts the data, without us needing to tell it to!

By contrast, most Abject-Oriented languages are either nominally typed—meaning that you give names to all of your types instead of meanings—or dynamically typed—meaning that your variables are all unique individuals that can accomplish anything if they try.

Memoization

Memoization means caching the results of a function call:

function getCustName(custID)
{
    if (custID == 3) { return "John Smith"; }
    custRec = readFromDB("customer", custID);
    fullname = custRec[1] + ' ' + custRec[2];
    return fullname;
}

Non-Strictness

Non-Strictness is often confused with Laziness, but in fact Laziness is just one kind of Non-Strictness. Here's an example that compares two different forms of Non-Strictness:

/****************************************
*
* TO DO:
*
* get tax rate for the customer state
* eventually from some table
*
****************************************/
// function lazyTaxRate(custId) {}

function callByNameTextRate(custId)
{
    /****************************************
    *
    * TO DO:
    *
    * get tax rate for the customer state
    * eventually from some table
    *
    ****************************************/
}

Both are Non-Strict, but the second one forces the compiler to actually compile the function just so we can Call it By Name. This causes code bloat. The Lazy version will be smaller and faster. Plus, Lazy programming allows us to create infinite recursion without making the program hang:

/****************************************
*
* TO DO:
*
* get tax rate for the customer state
* eventually from some table
*
****************************************/
// function lazyTaxRateRecursive(custId) { lazyTaxRateRecursive(custId); }

Laziness is often combined with Memoization:

function getCustName(custID)
{
    // if (custID == 3) { return "John Smith"; }
    custRec = readFromDB("customer", custID);
    fullname = custRec[1] + ' ' + custRec[2];
    return fullname;
}

Outside the world of Functional Addicts, this same technique is often called Test-Driven Development. If enough tests can be embedded in the code to achieve 100% coverage, or at least a decent amount, your code is guaranteed to be safe. But because the tests are not compiled and executed in the normal run, or indeed ever, they don't affect performance or correctness.

Conclusion

Many people claim that the days of Abject-Oriented Programming are over. But this is pure hype. Functional Addiction and Abject Orientation are not actually at odds with each other, but instead complement each other.
5

View comments

Blog Archive
About Me
About Me
Loading
Dynamic Views theme. Powered by Blogger. Report Abuse.