Explanation:
๐ธ a = [1, 2]
-
A list a is created with two elements:
๐ธ print(a[5])
-
This tries to access the element at index 5, which does not exist.
-
The valid indices for list a are 0 and 1.
-
So, Python raises an:
๐ธ except IndexError:
-
This catches the IndexError and runs the code inside the except block.
๐ธ print("oops")
-
Since an exception occurred, it prints:
✅ Output:
Key Concept:
-
Trying to access an invalid index in a list raises an IndexError.
try-except helps you gracefully handle such errors without crashing the program.


0 Comments:
Post a Comment