2 Python try-except

1. What is try-except?

try-except is used to handle errors in Python.

In simple words:
👉 Python tries to run some code
👉 If an error happens, Python does not stop
👉 Instead, Python runs the except part

2. Why Do We Need try-except?

Without try-except:

  • Program crashes

  • User sees scary error messages

With try-except:

  • Program runs smoothly

  • You can show friendly messages

3. Simple try-except Example

Example


 

Output:

Error happened

👉 Program does not crash.

4. try-except with Specific Error

It is better to catch specific errors.

Example


 

5. Handling Multiple Errors

Example


 

6. try-except-else

else runs only when no error happens.

Example


 

7. try-except-finally

finally runs always, error or not.

Example


 

8. try-except with User Input

Example


 

9. try-except with Files

Example


 

10. Catch Error Message

You can print the error message.

Example


 

11. Common Beginner Mistakes

❌ Using except without try


 

❌ Wrong.

❌ Catching All Errors Without Care


 

👉 Not good practice.

12. Simple Practice Examples

Example 1: Safe Division


 

Example 2: Input Check


 

Example 3: File Reading


 

13. Summary (Python try-except)

✔ Handles errors safely
✔ Prevents program crash
try runs risky code
except handles error
else and finally are optional

📘 Perfect for Beginner eBook

This chapter is ideal for:

  • Python beginner books

  • School & college students

  • Self-learners

If you want next, I can write:

  • raise Exception

  • Custom Exceptions

  • Debugging Python

  • Mini Python Projects

Just tell me 😊

You may also like...