✍️Introduction:
In Python, an exception is an error that occurs during program execution. If exceptions are not handled, the program stops suddenly.
Exceptions occur when unexpected situations happen, such as dividing by zero, opening a missing file, or entering invalid input.
By using exception handling, programmers can control these errors and display meaningful messages instead of stopping the program abruptly.
Exception Handling allows us to handle errors gracefully without crashing the program.
What is an Exception?
An exception is a runtime error.
An exception is generated when Python encounters an operation it cannot perform.
When an exception occurs, Python stops the normal flow of the program and raises an error message.
Exception handling helps manage these errors so the program can continue running instead of terminating.
Examples:
Dividing by zero
Accessing invalid index
Using wrong data type
Common Python Exceptions :
| Exception | Description |
|---|---|
| ZeroDivisionError | Division by zero |
| ValueError | Invalid value |
| TypeError | Wrong data type |
| IndexError | Invalid index |
| KeyError | Key not found |
By recognizing these exceptions, programs can respond properly instead of crashing unexpectedly.
Why Exception Handling is Important?
Prevents program crash
Improves user experience
Makes code robust
Used in real-world applications
Basic Exception Handling Syntax :
try:
# risky code
except:
# error handling code
The try-except block is used to handle errors in Python and prevent the program from crashing.
The code that may cause an error is written inside the try block.
If an exception occurs, Python immediately stops executing the try block and runs the except block to handle the error safely.
Example: Handling Division Error
try block.If a division by zero error occurs, Python jumps to the
except block and displays an error message instead of stopping the program.Output (example):
Using Specific Exception :
Handling a specific exception means catching a particular type of error instead of handling all errors.
Using specific exceptions like ValueError makes programs more precise and easier to debug.
It ensures that only the expected error is handled while other errors can still be detected.
Example:
try: num = int(input("Enter number: ")) # Takes input and converts to integer print(num) # Prints the number if valid except ValueError: # Handles invalid number input print("Invalid input") # Displays error messageExample Output (Invalid Input):
Enter number: abc
Invalid input"Code executed successfully"
Multiple Except Blocks :
Multiple except blocks allow a program to handle different types of exceptions separately.
Using multiple except blocks helps identify the exact error that occurs and handle it appropriately.
Python checks each except block in order and executes the one that matches the exception.
Example:
try: x = int("abc") # Tries to convert string to integer (causes ValueError) except ValueError: print("Value error") # Executes if ValueError occurs except TypeError: print("Type error") # Executes if TypeError occursOutput :
Value error"Code executed successfully"
else Block :
The else block runs when no exception occurs in the try block.
The else block is used to execute code only if the try block runs successfully without any errors.
This helps separate normal code from error-handling code, making programs easier to understand.
Example:
try: print(10 / 2) # Divides 10 by 2 (no error) except: print("Error") # Runs only if an error occurs else: print("Success") # Runs if no exception occursOutput :
5.0 Success"Code executed successfully"
finally Block :
The finally block always executes whether an exception occurs or not.
The finally block is used to run important code such as closing files or releasing resources.
It executes after the try and except blocks, ensuring cleanup operations always happen.
Example:
try: print(10 / 0) # Causes division by zero error except: print("Error occurred") # Handles the error finally: print("Program ended") # Always executesOutput :
Error occurred Program ended"Code executed successfully"
Raise an Exception :
Raising an exception means manually generating an error in a program using the raise keyword.
The raise statement is used when a program needs to stop execution if a certain condition is not met.
It helps enforce rules and ensures invalid data or conditions are not accepted.
Example:
age = 15 # Stores age value if age < 18: # Checks if age is less than 18 raise Exception("Not eligible to vote") # Raises an exception with messageOutput :
Exception: Not eligible to vote"Code executed successfully"⚠ Note:The program stops immediately when an exception is raised.
User-Defined Exception :
Exception class.This is useful when you want to define meaningful errors for specific conditions in your application.
Example:
class MyError(Exception): # Creates a custom exception class pass # No extra code needed raise MyError("This is a custom error") # Raises the custom exceptionOutput :
MyError: This is a custom error"Code executed successfully"⚠ Note:User-defined exceptions make programs easier to understand and debug.
Real-Life Example :
In real-world applications like banking systems, exceptions help enforce rules and prevent invalid operations.
If the withdrawal amount exceeds the balance, an exception is raised and handled gracefully instead of crashing the program.
Example:
try:
balance = 5000 # Stores account balance
withdraw = int(input("Enter amount: ")) # Takes withdrawal amount
if withdraw > balance: # Checks if amount exceeds balance
raise Exception("Insufficient balance") # Raises exception if true
print("Withdraw successful") # Executes if amount is valid
except Exception as e: # Catches the exception
print(e) # Prints error message
Example Output (Invalid Amount):
Enter amount: 7000
Insufficient balance
Example Output (Valid Amount):
Enter amount: 2000
Withdraw successful
"Code executed successfully"
❌ Common Mistakes:
Using only
exceptwithout specifying errorNot using
finallyfor cleanupIgnoring error messages
Difference: Error vs Exception
Errors and exceptions both indicate problems in a program, but they occur at different stages.
Errors usually happen due to mistakes in the code (like syntax errors) and prevent the program from running, while exceptions occur during execution and can be handled using exception handling techniques.
Exceptions allow programs to recover from unexpected situations, whereas errors generally need to be fixed before the program can run successfully.
| Error | Exception |
|---|---|
| Syntax mistake | Runtime issue |
| Cannot be handled | Can be handled |
| Program won’t run | Program runs |
Conclusion :
Exception handling is very important in Python programming.
It helps you write safe, stable, and professional programs.
💬 Interview Question :
What is the difference between finally and else?
Comment your answer 👇😊
📌 Related Articles
- Get link
- X
- Other Apps
Labels
Exception Handling- Get link
- X
- Other Apps
Comments
Post a Comment