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



 

Output:

Something went wrong!

🎯 Handling Specific Exceptions

Different errors need different handling.



 

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



 


🎛 Using else

else runs only if there is NO error.



 


🧹 Using finally

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



 


🧱 Combined Structure



 


🎯 Using raise (Manual Exception)

Force an error intentionally:


 


🎯 Catching Multiple Exceptions Together



 


🧰 Get Error Details



 

Output:

Error: division by zero

🧪 Real-Life Example: Input Validation



 


🚀 Real Example: Safe File Reading



 


📌 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

You may also like...