Day 11: Python Programming

Exception Handling

What is an Exception?

An exception is an error that occurs during the execution of a program.

Examples of common exceptions:

ZeroDivisionError
ValueError
TypeError
IndexError
FileNotFoundError
KeyError

Why Exception Handling?


This content originally appeared on DEV Community and was authored by Aruna Arun

Exception Handling

What is an Exception?

An exception is an error that occurs during the execution of a program.

Examples of common exceptions:

  • ZeroDivisionError
  • ValueError
  • TypeError
  • IndexError
  • FileNotFoundError
  • KeyError

Why Exception Handling?

Without handling → program crashes.
With handling → program continues safely.

try–except Block (Basic Syntax)
try:
# Code that may cause error
except:
# Code to run when error happens

Example
try:
x = 10 / 0
except:
print("Error occurred!")

Handling Specific Exceptions
try:
a = int("hello")
except ValueError:
print("Invalid number")

Multiple except Blocks
try:
num = int(input("Enter number: "))
print(10 / num)
except ZeroDivisionError:
print("Cannot divide by zero")
except ValueError:
print("Please enter digits only")

else Block
Runs only when no exception occurs.
try:
print("No error")
except:
print("Error found")
else:
print("Else block executed")

finally Block
Runs always, even if an error happens.

Useful for:

  • Closing files
  • Closing database connection
  • Releasing resources try: f = open("sample.txt", "r") print(f.read()) except: print("File not found") finally: print("Closing file")

try–except–else–finally (All Together)


python
try:
    n = int(input("Enter number: "))
except ValueError:
    print("Invalid Input")
else:
    print("Square:", n*n)
finally:
    print("End of program")

**Raise Your Own Exception**

Use `raise` to throw a custom error.
age = 15
if age < 18:
    raise Exception("You must be 18+")

**Custom Exception Class**
class LowBalanceError(Exception):
    pass
balance = 300
try:
    if balance < 500:
        raise LowBalanceError("Balance too low")
except LowBalanceError as e:
    print(e)

**Common Python Exceptions Table**

| Exception         | Meaning                 |
| ----------------- | ----------------------- |
| ZeroDivisionError | Division by zero        |
| ValueError        | Wrong value type        |
| TypeError         | Wrong data type         |
| IndexError        | List index out of range |
| KeyError          | Dictionary key missing  |
| FileNotFoundError | File does not exist     |
| ImportError       | Module not found        |


**Practical Mini Programs (Day 18 Practice)**

**1️⃣ Safe Division Program**
try:
    a = int(input("A: "))
    b = int(input("B: "))
    print(a / b)
except ZeroDivisionError:
    print("Cannot divide by zero")
except ValueError:
    print("Enter numbers only")

**2.File Reader with Exception Handling**
try:
    f = open("demo.txt", "r")
    print(f.read())
except FileNotFoundError:
    print("File doesn't exist")

**3.Convert String to Integer Safely**
def convert(s):
    try:
        return int(s)
    except:
        return "Conversion Failed"
print(convert("123"))
print(convert("abc"))

**4.Custom Exception **
**Example**
class InvalidAge(Exception):
    pass

try:
    age = int(input("Enter age: "))
    if age < 18:
        raise InvalidAge("Age is below 18")
    print("Eligible")
except InvalidAge as e:
    print(e)


This content originally appeared on DEV Community and was authored by Aruna Arun


Print Share Comment Cite Upload Translate Updates
APA

Aruna Arun | Sciencx (2025-11-30T16:00:01+00:00) Day 11: Python Programming. Retrieved from https://www.scien.cx/2025/11/30/day-11-python-programming/

MLA
" » Day 11: Python Programming." Aruna Arun | Sciencx - Sunday November 30, 2025, https://www.scien.cx/2025/11/30/day-11-python-programming/
HARVARD
Aruna Arun | Sciencx Sunday November 30, 2025 » Day 11: Python Programming., viewed ,<https://www.scien.cx/2025/11/30/day-11-python-programming/>
VANCOUVER
Aruna Arun | Sciencx - » Day 11: Python Programming. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2025/11/30/day-11-python-programming/
CHICAGO
" » Day 11: Python Programming." Aruna Arun | Sciencx - Accessed . https://www.scien.cx/2025/11/30/day-11-python-programming/
IEEE
" » Day 11: Python Programming." Aruna Arun | Sciencx [Online]. Available: https://www.scien.cx/2025/11/30/day-11-python-programming/. [Accessed: ]
rf:citation
» Day 11: Python Programming | Aruna Arun | Sciencx | https://www.scien.cx/2025/11/30/day-11-python-programming/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.