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 TypeMeaning
ValueErrorWrong data type
ZeroDivisionErrorDividing by zero
TypeErrorInvalid type operation
FileNotFoundErrorFile missing
IndexErrorInvalid list index
KeyErrorMissing 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

BlockRuns When
tryCode that may cause an error
exceptRuns if error occurs
elseRuns if no error occurs
finallyRuns 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...