0% found this document useful (0 votes)
9 views6 pages

Exception Hierarchy

Python has a structured Exception Hierarchy with all exceptions inheriting from BaseException, which includes system-exiting exceptions. The most commonly used class for user-defined exceptions is Exception, while specific error classes like ArithmeticError, LookupError, and OSError provide detailed categorization for debugging. It is recommended to catch specific exceptions rather than using a generic catch-all approach.

Uploaded by

vidhikapoor1298
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views6 pages

Exception Hierarchy

Python has a structured Exception Hierarchy with all exceptions inheriting from BaseException, which includes system-exiting exceptions. The most commonly used class for user-defined exceptions is Exception, while specific error classes like ArithmeticError, LookupError, and OSError provide detailed categorization for debugging. It is recommended to catch specific exceptions rather than using a generic catch-all approach.

Uploaded by

vidhikapoor1298
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Yes!

Python has a well-defined Exception Hierarchy where all exceptions inherit from
the built-in BaseException class.

Python Exception Hierarchy

BaseException

├── SystemExit

├── KeyboardInterrupt

├── GeneratorExit

└── Exception

├── ArithmeticError

│ ├── ZeroDivisionError

│ ├── FloatingPointError

│ ├── OverflowError

├── LookupError

│ ├── IndexError

│ ├── KeyError

├── OSError

│ ├── FileNotFoundError

│ ├── PermissionError

│ ├── TimeoutError

├── ValueError

├── TypeError

├── NameError

│ ├── UnboundLocalError

├── RuntimeError

│ ├── RecursionError

├── AssertionError

├── AttributeError

├── EOFError

├── ImportError

│ ├── ModuleNotFoundError

├── KeyboardInterrupt

├── IndentationError

│ ├── TabError

├── MemoryError

├── NotImplementedError

├── RecursionError

1. BaseException (Root of All Exceptions)

 All exceptions in Python inherit from BaseException.

 Normally, we should not catch BaseException as it includes system-exiting


exceptions like KeyboardInterrupt.

2. Exception (General Exception Class)

 The most common class that all user-defined exceptions inherit from.

 It is safe to catch Exception because it excludes system-exiting errors.

Example: Catching Exception


try:

x=1/0

except Exception as e:

print("Caught an exception:", e)

Output:

Caught an exception: division by zero

3. ArithmeticError (Math-Related Errors)

 ZeroDivisionError → Division by zero

 OverflowError → Too large number to store

 FloatingPointError → Floating point operation failure (rare)

Example: ZeroDivisionError

try:

print(10 / 0)

except ZeroDivisionError:

print("Cannot divide by zero!")

4. LookupError (Container Access Errors)

 IndexError → List index out of range

 KeyError → Dictionary key does not exist

Example: IndexError

my_list = [1, 2, 3]

try:

print(my_list[5]) # Invalid index

except IndexError:

print("Index out of range!")

5. OSError (File and OS-Related Errors)


 FileNotFoundError → File does not exist

 PermissionError → No permission to access a file

Example: FileNotFoundError

try:

open("non_existent_file.txt", "r")

except FileNotFoundError:

print("File not found!")

6. TypeError (Invalid Data Type Usage)

Occurs when an operation is performed on an incorrect type.

Example: TypeError

try:

print("Hello" + 5)

except TypeError:

print("Cannot concatenate string and integer!")

7. ValueError (Incorrect Value)

Occurs when a function receives an argument of the correct type but invalid value.

Example: ValueError

try:

num = int("abc") # Cannot convert "abc" to integer

except ValueError:

print("Invalid number format!")

8. ImportError (Module Import Issues)

 ModuleNotFoundError → Module not found

 ImportError → Cannot import a function from a module

Example: ModuleNotFoundError
try:

import non_existent_module

except ModuleNotFoundError:

print("Module not found!")

9. NameError (Undefined Variables)

 UnboundLocalError → Using a local variable before assignment

Example: NameError

try:

print(undefined_variable)

except NameError:

print("Variable not defined!")

10. RuntimeError (General Runtime Errors)

 RecursionError → Maximum recursion depth exceeded

Example: RecursionError

def recursive_function():

return recursive_function()

try:

recursive_function()

except RecursionError:

print("Recursion depth exceeded!")

Key Takeaways

✔ Python exceptions follow a hierarchical structure


✔ BaseException is the root, but Exception is the most commonly used parent
✔ Specific errors like TypeError, ValueError, IndexError, etc., help in debugging
✔ Always catch specific exceptions instead of using a generic except:
Would you like any deep dive into a specific category?

You might also like