Search code examples
pythonindentation

Why do I get an IndentationError from a properly indented function (following a "try" with no "except")?


I have some code like:

def first_function(x):
    try:
        return do_something_else()
def second_function(x, y, z):
    pass

But I get an error like:

    def second_function(x, y, z):
    ^
IndentationError: unexpected unindent

The indentation uses only spaces and everything lines up properly. What is wrong?


This question is specifically about the fact that a try block requires a corresponding except or finally. Some older versions of Python will detect this as an IndentationError for subsequent code, because it's expecting that code to be "inside the try" when an except or finally hasn't been seen yet. More recent versions of Python may report the error differently.

See also I'm getting an IndentationError (or a TabError). How do I fix it? for general information about IndentationError.

See also Why do I get a SyntaxError (or an IndentationError) in a line with perfectly valid syntax? for another common case where a syntax issue is reported in a misleading way.


Solution

  • It's because you have:

    def first_function(x):
        try:
            return do_something_else()
    

    without a matching except block after the try: block. Every try must have at least one matching except.

    See the Errors and Exceptions section of the Python tutorial.