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

Understanding Exception Hierarchy

Sveip for å vise menyen

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?

Velg det helt riktige svaret

question mark

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

Velg det helt riktige svaret

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 1. Kapittel 1

Spør AI

expand

Spør AI

ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

Seksjon 1. Kapittel 1
some-alt