Loading Page Content...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
Errors in Python fall into two broad categories: Syntax Errors (detected by the parser before code execution begins) and Exceptions (anomalies detected during execution at runtime). When an exception is not intercepted, Python halts program execution and displays a traceback.
All built-in exceptions form an inheritance tree rooted at BaseException. Understanding this hierarchy prevents bugs where catching a broad exception inadvertently intercepts system-level termination signals.
except BaseException:. Doing so catches KeyboardInterrupt and SystemExit, making it impossible to stop your program using Ctrl+C.TypeError vs. ValueErrorTypeError: An operation or function is applied to an object of inappropriate type.ValueError: The type is correct, but the content / value is invalid.LookupError: IndexError vs. KeyErrorIndexError: Attempting to access an index outside the boundaries of a sequence (list, tuple).KeyError: Looking up a dictionary key that does not exist.AttributeErrorOccurs when attempting to access a method or attribute that does not exist on that object type:
NameError vs. UnboundLocalErrorNameError: Referencing a variable or function name that has not been defined in any local, enclosing, or global scope.UnboundLocalError: Referencing a local variable before it has been assigned inside a function.ModuleNotFoundErrorA specialized subclass of ImportError raised when Python cannot resolve an import target:
Because exceptions are standard Python classes, catching a parent class catches all derived subclasses:
BaseException BlindlyCatching BaseException catches KeyboardInterrupt (Ctrl+C) and SystemExit, making your script unkillable from the terminal! Always inherit from and catch Exception.
ValueError with TypeErrorTypeError: An argument is of the wrong type (e.g. passing a string to math.sqrt()).ValueError: An argument is of the right type but inappropriate value (e.g. math.sqrt(-1)).Write a script that prompts the user for their age. Handle both ValueError (if non-numeric string is entered) and custom range validation without crashing.
int("ninety-nine")?IndexError and KeyError inherit directly from which intermediate class?except BaseException: in normal application code?(5).append(10)?In the next lesson, we will continue your intermediate Python journey with Try-Except-Else-Finally (6: Exception Handling).
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| Project: Bank Account Class System | Try-Except-Else-Finally |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.