⭐ Exception Handling in Python
Exception Handling is a mechanism used to detect and manage errors during program execution.
Instead of crashing the program when an error occurs, Python provides a safe way to handle it and continue execution.
⭐ What Is Exception Handling? (Exam Definition)
Exception handling is the process of responding to runtime errors (exceptions) in a controlled manner using try, except, else, finally, and raise statements.
It prevents the program from terminating unexpectedly.
⭐ Why Do We Need Exception Handling?
✔ Prevent program crashes
✔ Handle errors gracefully
✔ Provide meaningful error messages
✔ Improve user experience
✔ Allow program to continue execution
✔ Debugging becomes easier
⭐ Basic Exception Handling Structure
Python uses the following syntax:
try:
# Code that may cause an exception
except:
# Code to handle the exception
⭐ Example 1: Basic try-except
try:
x = 10 / 0
except:
print("Error: Cannot divide by zero")
Output:
Error: Cannot divide by zero
⭐ Multiple Except Blocks
Used to handle specific exceptions:
try:
a = int("abc")
except ValueError:
print("Value Error occurred")
except TypeError:
print("Type Error occurred")
⭐ Catching Multiple Exceptions in One Line
try:
x = 10 + "Hello"
except (TypeError, ValueError):
print("Some error occurred")
⭐ Using Exception Object
try:
x = 10 / 0
except Exception as e:
print("Exception:", e)
⭐ The else Block
The else block executes only when no exception occurs.
try:
x = int("123")
except ValueError:
print("Invalid input")
else:
print("Conversion successful:", x)
⭐ The finally Block
The finally block always executes, whether an exception occurs or not.
Useful for cleanup tasks: closing files, releasing resources, etc.
try:
f = open("myfile.txt")
data = f.read()
except FileNotFoundError:
print("File does not exist")
finally:
print("Execution completed!")
⭐ try-except-else-finally (Full Structure)
try:
# risky code
except:
# handle error
else:
# runs when no error
finally:
# always runs
⭐ Raising Exceptions (raise)
Used to throw an exception manually.
age = -5
if age < 0:
raise ValueError("Age cannot be negative")
⭐ User-Defined Exceptions
You can create your own exceptions using classes.
class MyError(Exception):
pass
try:
raise MyError("Something went wrong!")
except MyError as e:
print(e)
⭐ Practical Example: Handling Multiple Errors
try:
a = int(input("Enter number: "))
b = int(input("Enter another: "))
print(a / b)
except ValueError:
print("Invalid number")
except ZeroDivisionError:
print("You cannot divide by zero!")
except Exception as e:
print("Unknown error:", e)
finally:
print("Program finished")
⭐ Flow of Exception Handling
- Code inside
tryexecutes - If an exception occurs → Python jumps to matching
exceptblock - If no exception occurs →
elseexecutes finallyexecutes in all cases
⭐ Advantages of Exception Handling
✔ Prevents abnormal termination
✔ Improves reliability
✔ Separates error-handling logic from normal logic
✔ Makes programs robust and maintainable
⭐ Exam-Ready Summary
- Exceptions are runtime errors that stop program execution
- Python handles them using
try,except,else,finally,raise try: code that may cause errorexcept: handles errorelse: runs if no error occursfinally: always runs- Custom exceptions can be created using classes
