u5-script-exceptions Flashcards

1
Q

What’s the basic structure of a try-except block in Python?

A
try:
    # code that might raise exception
except ExceptionType as e:
    # code to handle the exception
    print(f"Error: {e}")
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What’s the difference between except ValueError and except (ValueError, TypeError)?

A

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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is the purpose of the ‘as’ keyword in except statements?

A

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}")```
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What’s the difference between else and finally in try blocks?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How do you re-raise an exception in an except block?

A

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```
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What happens when you have nested try-except blocks?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How do you create a custom error message while preserving the original exception?

A

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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What’s the difference between catching a specific exception vs all exceptions?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How can you handle KeyError when accessing dictionary values?

A

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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What’s the purpose of multiple except blocks?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

How do exceptions affect program flow in Python?

A

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")```
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What’s the proper way to handle conversion errors in Python?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

How do you ensure cleanup code always runs, even if exceptions occur?

A

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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly