Back to Study Material Python

Exception Handling

Exception handling in Python lets your program respond to errors gracefully instead of crashing. Python uses four keywords for this: try, except, else, and...

Exception Handling

Exception Handling in Python: try, except, else, and finally

Exception handling in Python lets your program respond to errors gracefully instead of crashing. Python uses four keywords for this: try, except, else, and finally. Each plays a distinct role, and understanding all four gives you precise control over how errors are handled.

The try block contains code that might raise an exception. If an exception occurs, Python immediately stops executing the try block and looks for a matching except clause. If a match is found, the code in that except block runs. If no match is found, the exception propagates up the call stack.

try: result = 10 / int(input("Enter a number: ")) except ZeroDivisionError: print("Cannot divide by zero.") except ValueError: print("Please enter a valid integer.") else: print(f"Result is {result}") finally: print("This always runs.")

The else block runs only if no exception was raised in the try block. This is useful for code that should execute on success but not on failure, and it keeps the try block focused on just the risky operation. The finally block always runs, regardless of whether an exception occurred. It is the right place to put cleanup code such as closing files or releasing resources.

You can catch multiple exception types in a single except clause by grouping them in a tuple:

except (ValueError, TypeError) as e: print(f"Input error: {e}")

The as keyword lets you capture the exception object and inspect it. You can access its message, its type, and any custom attributes if it is a custom exception.

Python also allows you to re-raise an exception inside an except block using a bare raise statement. This is useful when you want to log the error or perform some cleanup and then let the exception continue propagating.

Exam tip: Many students forget that else in a try/except runs only when no exception is raised. This is different from else in a loop, where it runs when the loop completes without a break. Make sure you know both uses. Also remember that finally runs even if there is a return statement inside the try block.