Python Try…Except

⚠️ Python Try…Except (Exception Handling)

Errors (called exceptions) stop a program from running.
To prevent this crash, we use try-except to handle errors safely.


✅ Basic Try-Except Example

try:
print(10 / 0)
except:
print("Something went wrong!")

Output:

Something went wrong!

🎯 Handling Specific Exceptions

Different errors need different handling.

try:
x = int("Hello")
except ValueError:
print("Invalid number!")

Common exceptions:

Error Type Meaning
ValueError Wrong data type
ZeroDivisionError Dividing by zero
TypeError Invalid type operation
FileNotFoundError File missing
IndexError Invalid list index
KeyError Missing dictionary key

🔥 Multiple Except Blocks

try:
a = 10 / 0
except ZeroDivisionError:
print("You cannot divide by zero!")
except ValueError:
print("Invalid value!")

🎛 Using else

else runs only if there is NO error.

try:
num = int("50")
except:
print("Error occurred")
else:
print("Success! Value =", num)

🧹 Using finally

finally always runs — even if there is an error.
Useful for closing files, database connections, etc.

try:
file = open("test.txt")
print(file.read())
except FileNotFoundError:
print("File not found!")
finally:
print("Done running code.")

🧱 Combined Structure

try:
# risky code
except:
# if error occurs
else:
# if no error
finally:
# always runs

🎯 Using raise (Manual Exception)

Force an error intentionally:

x = -5

if x < 0:
raise ValueError("Age cannot be negative!")


🎯 Catching Multiple Exceptions Together

try:
x = 10 / 0
except (ZeroDivisionError, TypeError, ValueError):
print("An error occurred!")

🧰 Get Error Details

try:
print(10 / 0)
except Exception as e:
print("Error:", e)

Output:

Error: division by zero

🧪 Real-Life Example: Input Validation

try:
age = int(input("Enter age: "))
print("Your age:", age)
except ValueError:
print("Please enter a valid number!")

🚀 Real Example: Safe File Reading

try:
with open("data.txt") as file:
print(file.read())
except FileNotFoundError:
print("Error: File does not exist!")

📌 Summary Table

Block Runs When
try Code that may cause an error
except Runs if error occurs
else Runs if no error occurs
finally Runs always

🧠 Practice Tasks

✔ Write code that prevents division by zero
✔ Handle wrong user input (only numbers allowed)
✔ Catch and display file errors

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *