In Python, runtime errors (exceptions) can stop your program from executing. To prevent sudden crashes and handle problems gracefully, you use try, except, else, and finally blocks.
The idea: put “risky” code inside try. If an error occurs, the corresponding except block runs instead of the program crashing.
try – contains the code that might raise an exception.except – handles the error if one occurs.ValueError, ZeroDivisionError, etc.else – runs only if no exception was raised in the try block.finally – always runs, whether an error occurred or not (often used for cleanup).except blocks – to handle different exception types differently.General structure of exception handling in Python:
try:
# code that may raise an exception
except SomeExceptionType:
# handle specific exception
except AnotherExceptionType:
# handle another exception
else:
# runs if no exception was raised
finally:
# runs no matter what (cleanup code)
The else and finally blocks are optional, but they help separate “normal success code” (else) from “always-run cleanup code” (finally).
This example catches any exception and prints a friendly message instead of crashing.
try:
# risky operation: may raise ZeroDivisionError
x = 10 / 0
except:
# generic error handler
print("Something went wrong!")
It is better to catch specific exception types like ValueError so that unexpected errors don’t get silently swallowed.
try:
# convert string to integer (this will fail)
num = int("hello")
except ValueError:
# handle invalid integer conversion
print("Invalid number!")
The else block runs only when the try block does not raise any exception.
try:
# code that may raise an exception
print("No error here")
except:
# runs if an exception is raised
print("Error occurred")
else:
# runs only if no exception was raised
print("Everything worked fine!")
The finally block is mainly used for cleanup actions such as closing files or network connections.
try:
# attempt to open and read a file
f = open("file.txt")
f.read()
except FileNotFoundError:
# handle missing file error
print("File not found")
finally:
# cleanup or final message that always runs
print("This will always run")
You can handle different types of errors separately using multiple except blocks.
try:
# this line may raise ValueError or ZeroDivisionError
x = int("text") / 0
except ValueError:
# handle invalid integer conversion
print("Value error occurred")
except ZeroDivisionError:
# handle division by zero
print("Cannot divide by zero")
Code: dividing by zero inside the try block.
Without exception handling, Python would raise ZeroDivisionError and stop the program.
With the try-except block, the output is:
Something went wrong!
When Python tries to run int("hello"), it fails because the string "hello" cannot be converted to an integer. This raises a ValueError.
The except ValueError block catches it and prints:
Invalid number!
try block, the else block runs.finally block always runs, whether an exception happened or not.This separation helps you clearly express: “what happens on success”, “what happens on error”, and “what must happen in all cases”.
ValueError, ZeroDivisionError) instead of a bare except:.finally for cleanup tasks such as closing files, network connections, or database cursors.try blocks small and focused so that you don’t accidentally hide unrelated bugs.except blocks to make debugging easier.else for code that should only run when everything in try succeeds.input(). Handle non-numeric input using try-except and show a friendly error message.FileNotFoundError. Print a message like "File does not exist".try-except-else-finally:
try – read a number and divide 100 by it.except – handle invalid input or division by zero.else – print the result if everything went well.finally – print a message like "Program ended".