u5-script-exceptions Flashcards
What’s the basic structure of a try-except block in Python?
try: # code that might raise exception except ExceptionType as e: # code to handle the exception print(f"Error: {e}")
What’s the difference between except ValueError and except (ValueError, TypeError)?
The first catches only ValueError, while the second catches both. Example:
try: result = numerator / denominator except (ValueError, TypeError) as ex: # Catches both print(f"Warning: {ex}") return None
What is the purpose of the ‘as’ keyword in except statements?
It captures the exception object in a variable, allowing you to access its details. Example:
try: result = 1 / 0 except ZeroDivisionError as e: print(f"Error details: {e}")```
What’s the difference between else and finally in try blocks?
else runs only if no exception occurred, finally runs always regardless of exceptions. Example:
try: x = 1/1 except ZeroDivisionError: print("division error") else: print("success") # runs if no exception finally: print("cleanup") # always runs```
How do you re-raise an exception in an except block?
Use the ‘raise’ keyword without arguments to re-raise the caught exception. Example:
try: x = int("invalid") except ValueError as e: print("Converting failed") raise # Re-raises the ValueError```
What happens when you have nested try-except blocks?
Each try-except handles exceptions in its scope. If an exception isn’t caught, it propagates to outer blocks. Example:
try: try: 1/0 except TypeError: # Won't catch ZeroDivisionError print("Type error") except ZeroDivisionError: # Catches it here print("Division error")```
How do you create a custom error message while preserving the original exception?
Use ‘raise from’ to chain exceptions while keeping the original cause. Example:
try: int("abc") except ValueError as e: raise RuntimeError("Invalid input") from e
What’s the difference between catching a specific exception vs all exceptions?
Specific catches (except ValueError) are preferred as they handle known cases. Catching all (except:) can hide bugs. Example:
try: value = int("abc") except ValueError: # Good: specific print("Invalid number") except: # Bad: catches everything```
How can you handle KeyError when accessing dictionary values?
Use try-except to catch KeyError or use dict.get() method. Example:
def get_value(d: dict, key, default=None): try: return d[key] except KeyError: return default
What’s the purpose of multiple except blocks?
They allow different handling for different types of exceptions. Example:
try: result = num/divisor except ZeroDivisionError: print("Cannot divide by zero") except TypeError: print("Invalid operand types")```
How do exceptions affect program flow in Python?
When an exception occurs, Python immediately jumps to the matching except block, skipping remaining try block code. Example:
try: print("Start") 1/0 # Exception occurs print("Never reaches here") except ZeroDivisionError: print("Caught error")```
What’s the proper way to handle conversion errors in Python?
Chain multiple try-except blocks or use multiple except clauses. Example:
def add(a, b): try: return a + b except TypeError: try: return int(a) + int(b) except ValueError: try: return float(a) + float(b) except ValueError: raise # Re-raise original TypeError
How do you ensure cleanup code always runs, even if exceptions occur?
Use a finally block, which executes whether an exception occurred or not. Example:
file = open("data.txt") try: data = file.read() except IOError: print("Error reading file") finally: file.close() # Always closes file