Monday, 20 July 2026

πŸš€ Day 90/150 – Exception Handling in Python

 

πŸš€ Day 90/150 – Exception Handling in Python

Errors are unavoidable in programming, but they don't have to crash your program. Python provides exception handling to detect errors and respond to them gracefully. By using try, except, else, and finally, you can make your programs more reliable and user-friendly.

In this post, we'll explore four common ways to handle exceptions in Python.

Method 1 – Using try and except

This is the most basic way to catch an exception and prevent your program from crashing.

try: #The try block contains the code that might cause an error. num = int(input("Enter a number: ")) print(10 / num) except ZeroDivisionError: #The except block contains the code that should run if an error occurs inside the try block. print("Cannot divide by zero!")





Sample Input

0

Output
Cannot divide by zero!

Explanation

  • The code inside the try block is executed first.
  • If the user enters 0, dividing by zero raises a ZeroDivisionError.
  • The except block catches the error and displays a friendly message instead of terminating the program.

Method 2 – Handling Multiple Exceptions

A program can encounter different types of errors. Python allows you to handle each one separately.

try: num = int(input("Enter a number: ")) print(10 / num) except ZeroDivisionError: print("Division by zero is not allowed.") except ValueError: print("Please enter a valid number.")





Sample Input

abc

Output
Please enter a valid number.

Explanation

  • ValueError occurs when the input cannot be converted to an integer.
  • ZeroDivisionError occurs when attempting to divide by zero.
  • Separate except blocks make error handling more specific and readable.

Method 3 – Using else and finally

The else block runs only when no exception occurs, while the finally block always executes.

try: num = int(input("Enter a number: ")) result = 100 / num except ZeroDivisionError: print("Cannot divide by zero.") else: print("Result:", result) finally: print("Program finished.")












Sample Input
5
Output
Result: 20.0 
Program finished.

Explanation

  • else executes only if the try block completes successfully.
  • finally runs whether an exception occurs or not.
  • finally is commonly used for cleanup tasks such as closing files or database connections.

Method 4 – Catching Any Exception

Sometimes you may want to catch unexpected errors using the base Exception class.


try: num = int(input("Enter a number: ")) print(10 / num) except Exception as error: print("An error occurred:", error)







Sample Input
hello

Output

An error occurred: invalid literal for int() with base 10: 'hello'

Explanation
  • Exception catches most runtime errors.
  • The exception object is stored in the variable error.
  • This method is useful for debugging, but catching specific exceptions is generally considered better practice.

Comparison of Methods

MethodBest Used For
try + exceptHandling a single expected exception
Multiple except blocksHandling different types of errors separately
else + finallyRunning success code and cleanup tasks
except ExceptionCatching unexpected runtime errors

πŸ”₯ Key Takeaways

  • Exception handling prevents your program from crashing unexpectedly.
  • Use try and except to catch errors safely.
  • Handle specific exceptions whenever possible for clearer code.
  • Use else for code that should run only if no exception occurs.
  • Use finally for cleanup operations that must always execute.
  • Avoid relying on except Exception unless you genuinely need to catch unexpected errors.

0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (119) AI (315) Android (25) AngularJS (1) Api (7) Assembly Language (2) aws (31) Azure (12) BI (10) book (1) Books (296) Bootcamp (12) C (78) C# (12) C++ (83) cloud (1) Course (87) Coursera (302) Cybersecurity (33) data (9) Data Analysis (40) Data Analytics (28) data management (16) Data Science (400) Data Strucures (23) Deep Learning (203) Django (16) Downloads (3) edx (21) Engineering (15) Euron (30) Events (7) Excel (24) Finance (11) flask (4) flutter (1) FPL (17) Generative AI (76) Git (12) Google (53) Hadoop (3) HTML Quiz (1) HTML&CSS (48) IBM (43) IoT (3) IS (25) Java (99) Leet Code (4) Machine Learning (355) Meta (24) MICHIGAN (5) microsoft (13) Nvidia (8) Pandas (15) PHP (20) Projects (34) Python (1407) Python Coding Challenge (1202) Python Mathematics (6) Python Mistakes (51) Python Quiz (576) Python Tips (27) Questions (3) R (72) React (7) Scripting (3) security (4) Selenium Webdriver (4) Software (21) SQL (52) Udemy (18) UX Research (1) web application (11) Web development (9) web scraping (3)

Followers

Python Coding for Kids ( Free Demo for Everyone)