try, except, else & finallyGet Certified
Handling Errors Gracefully
Exception handling helps your Python programs respond to unexpected situations without stopping abruptly. An exception can occur because of invalid input, an impossible calculation, or a missing resource. By placing risky operations inside a try block, you can decide how the program should respond when a problem occurs. Understanding these clauses makes your code more reliable and easier to maintain.
When a program encounters a problem it cannot solve, Python raises an exception. If the exception is not handled, the program stops and shows a traceback. The try / except / else / finally structure lets you catch problems, recover from them, and still clean up resources.
- try – the block of code you want to attempt.
- except – the block that runs when a specific error occurs.
- else – runs only when the try block finishes with no exception.
- finally – always runs, whether an exception happened or not.
Basic try / except
A try block contains statements that may produce an exception during execution. If an error occurs, Python looks for an except block that matches the exception type. When a matching handler is found, its statements run and execution continues after the structure. Use this pattern when you can provide a useful response to a specific error.
The simplest pattern wraps risky code in a try block and provides one or more except handlers.
Try It: Catching Division by Zero
print("Emily is calculating a ratio in Chicago.")
try:
result = 100 / 0
print("Result:", result)
except ZeroDivisionError:
print("Cannot divide by zero. Please check the values.")
print("Program continues normally.")Try It: Handling Invalid Input
print("Jake in Austin is asking for an age.")
try:
age = int(input("Enter your age: "))
print("You entered:", age)
except ValueError:
print("That was not a valid whole number.")
print("Thanks for trying.")Multiple except Blocks
Different operations can raise different types of exceptions, so one handler may not be enough. You can add multiple except blocks to respond to each expected error separately. Python checks the handlers in order and executes the first one that matches the raised exception. Keep specific exception types before broader handlers to make the behavior predictable.
You can write several except clauses to handle different kinds of problems in different ways.
Try It: Different Handlers for Different Errors
print("Sophia in Seattle is converting and dividing.")
text = "abc"
try:
number = int(text)
result = 50 / number
print("Result:", result)
except ValueError:
print("Could not convert the text to a number.")
except ZeroDivisionError:
print("The number was zero, so division failed.")
print("Finished handling the attempt.")The else Clause
The else clause separates successful operations from exception-handling code. Python executes it only when every statement in the try block completes without raising an exception. This makes it useful for displaying results or performing follow-up work after a successful operation. If an exception occurs, Python skips else and moves to the matching except handler.
The else block runs only when the try block completes without raising any exception. It is a good place for code that should run only on success.
Try It: else Runs on Success
print("Liam in Denver is testing a successful path.")
try:
value = int("25")
half = value / 2
except ValueError:
print("Conversion failed.")
else:
print("Conversion succeeded. Half is", half)
print("End of example.")The finally Clause
The finally clause is designed for statements that must run whether an operation succeeds or fails. It is commonly used to close files, release resources, or perform other cleanup tasks. Python runs finally after the try and any matching except or else block has finished. This helps ensure that important cleanup work is not accidentally skipped when an error occurs.
finally always runs, whether an exception was raised or not. It is ideal for cleanup actions such as closing files or releasing resources.
Try It: finally Always Executes
print("Olivia in Boston is testing finally.")
try:
result = 10 / 0
except ZeroDivisionError:
print("Division by zero was caught.")
finally:
print("This cleanup message always appears.")
print("Program continues.")Try It: Full try / except / else / finally
print("Noah in Portland is using the full structure.")
try:
number = int("40")
print("Converted number:", number)
except ValueError:
print("Conversion failed.")
else:
print("No errors occurred.")
finally:
print("Finally block is finished.")
print("All done.")Accessing the Exception Object
An except clause can use the as keyword to store the caught exception in a variable. That variable gives you access to the exception object and its message. You can use the details to explain the problem, record diagnostic information, or make a suitable decision. Choose a clear variable name so the purpose of the captured exception is easy to understand.
You can capture the exception instance with as and inspect its message or type.
Try It: Printing the Error Message
print("Ava in Minneapolis is inspecting the error.")
try:
value = int("hello")
except ValueError as err:
print("Something went wrong.")
print("Details:", err)
print("Example complete.")Try It: Raising an Exception on Purpose
print("Ethan in Dallas is validating a temperature.")
temp = -5
try:
if temp < 0:
raise ValueError("Temperature cannot be negative.")
print("Temperature is acceptable.")
except ValueError as err:
print("Validation failed:", err)
print("Check complete.")Best Practices
Good exception handling makes programs more predictable without hiding genuine programming problems. Handle only errors that your application can reasonably respond to, and keep protected code focused. Provide messages that help users understand what happened while keeping technical details useful for debugging. Use finally for cleanup and avoid broad handlers that silently ignore unexpected failures.
- Catch only the exceptions you expect and know how to handle.
- Keep try blocks small so it is clear which statement might fail.
- Use else for code that should run only when no exception occurred.
- Put cleanup actions in finally so they always execute.
- Prefer specific exception types over a bare
except:. - When you raise an exception yourself, supply a clear, helpful message.
Key Takeaways
The try, except, else, and finally clauses work together to control how a program responds to exceptions. The except clause handles matching errors, while else runs only after a successful try block. The finally clause provides a place for cleanup that must happen in either case. You can also inspect exception objects and raise your own exceptions when a condition is invalid.
trycontains the code that might raise an exception.excepthandles one or more specific exception types.elseruns only when the try block succeeds completely.finallyalways runs and is ideal for cleanup.- You can capture the exception object with
asand inspect its message. - Use
raiseto signal an error condition from your own code.
Frequently Asked Questions
The questions below cover common points that arise when learning Python exception handling. They explain how the clauses behave, how multiple handlers are selected, and what happens when an error is not caught. Reviewing these answers can help clarify details that may not be obvious from a short code example. Use the examples above to connect each answer with the way Python executes exception-handling code.
What is the difference between else and finally?
The else block runs only when the try block finishes without any exception. The finally block runs no matter what—whether an exception occurred, was handled, or the try block succeeded. finally is for cleanup; else is for the pure success path.
Can I have multiple except blocks?
Yes. You can list several except clauses, each targeting a different exception type. Python checks them in order and runs the first matching handler. More specific exceptions should appear before more general ones.
What happens if no except matches the exception?
The exception continues to propagate. If nothing higher up the call stack handles it, the program terminates and displays a traceback. That is why it is important to catch the errors you can recover from.
Should I use a bare except: clause?
A bare except: catches every exception, including SystemExit and KeyboardInterrupt. This can hide serious problems. Prefer catching specific exception types so you only handle the errors you expect.
When should I raise an exception myself?
Raise an exception when your code detects a condition it cannot handle correctly— for example an invalid argument, a missing required value, or a business rule violation. Supply a clear message so the caller knows what went wrong.
Does finally run if I return inside try or except?
Yes. Even if a return statement is executed inside the try or except block, the finally block still runs before the function actually returns. This guarantees cleanup code is not skipped.
Can I use try without an except?
You can write try/finally without any except. In that case any exception will still propagate after the finally block finishes, but the cleanup code is guaranteed to run first.
How do I see the full error details while developing?
During development you can catch the exception, print it, and also re-raise it with a bare raise statement inside the except block. That way you see the message and still get the full traceback.