Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lära Understanding Exception Hierarchy | Comprehensive Error Handling (Exceptions)
Python Structural Programming

Understanding Exception Hierarchy

Svep för att visa menyn

When you work with error handling in Python, it's important to understand the structure of its built-in exception classes. All exceptions inherit from the root class BaseException. Most you will handle in everyday code are subclasses of Exception, which itself is a direct child of BaseException. This design lets you catch broad categories of errors or handle specific problems.

Commonly used exceptions like ValueError, TypeError, KeyError, and IOError (also known as OSError in modern Python) are all subclasses of Exception. There are also more specialized exceptions, such as ZeroDivisionError and IndexError, which inherit from these general classes. Some exceptions, like KeyboardInterrupt and SystemExit, inherit directly from BaseException - these are usually not meant to be caught in normal programs.

Understanding this hierarchy helps you write precise try/except blocks, catching only what you intend and avoiding masking critical system signals.

1234567891011121314151617181920212223242526272829303132
def raise_and_catch_exceptions(): # Catching a ValueError try: int("not a number") except ValueError as ve: print("Caught ValueError:", ve) # Catching a ZeroDivisionError (subclass of ArithmeticError) try: result = 10 / 0 except ZeroDivisionError as zde: print("Caught ZeroDivisionError:", zde) # Catching a TypeError try: result = "10" + 5 except TypeError as te: print("Caught TypeError:", te) # Catching an OSError (formerly IOError) try: open("file_that_does_not_exist.txt") except OSError as oe: print("Caught OSError:", oe) # Catching a general Exception (will catch most, but not all, exceptions) try: raise KeyError("missing key") except Exception as e: print("Caught Exception:", type(e).__name__, "-", e) raise_and_catch_exceptions()

1. Which built-in exception class would you use to catch errors when trying to convert a string to an integer that cannot be converted?

2. Which built-in exception is raised when you try to access a dictionary key that does not exist?

question mark

Which built-in exception class would you use to catch errors when trying to convert a string to an integer that cannot be converted?

Vänligen välj det korrekta svaret

question mark

Which built-in exception is raised when you try to access a dictionary key that does not exist?

Vänligen välj det korrekta svaret

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 1. Kapitel 1

Fråga AI

expand

Fråga AI

ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

Avsnitt 1. Kapitel 1
some-alt