How do you handle exceptions in python? Flashcards

(6 cards)

1
Q

key components of exception handling

A
  • Try: The section of code where exceptions might occur is placed within a try block.
  • Except: Any possible exceptions that are raised by the try block are caught and handled in the except block.
  • Finally: This block ensures a piece of code always executes, regardless of whether an exception occurred. It’s commonly used for cleanup operations, such as closing files or database connections.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Generic Exception Handling vs. Handling Specific Exceptions

A
  • It’s good practice to handle specific exceptions when possible.
  • However, a more general approach can also be taken. When doing the latter, ensure the general exception handling is at the end of the chain.
try:
    risky_operation()
except IndexError:  # Handle specific exception types first.
    handle_index_error()
except Exception as e:  # More general exception must come last.
    handle_generic_error()
finally:
    cleanup()
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Raising Exceptions

A
  • Use this mechanism to trigger and manage exceptions under specific circumstances. This can be particularly useful when building custom classes or functions where specific conditions should be met.
  • Raise a specific exception:
def divide(a, b):
    if b == 0:
        raise ZeroDivisionError("Divisor cannot be zero")
    return a / b

try:
    result = divide(4, 0)
except ZeroDivisionError as e:
    print(e)
  • Raise a general exception:
def some_risky_operation():
    if condition: 
        raise Exception("Some generic error occurred")
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Using “with” for Resource Management

A

File is automatically closed when the block is exited

  • The with keyword provides a more efficient and clean way to handle resources, like files, ensuring their proper closure when operations are complete or in case of any exceptions.
  • The resource should implement a context manager, typically by having __enter__ and __exit__ methods.
with open("example.txt", "r") as file:
    data = file.read()
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Callback Function: ExceptionHook

A

Python 3 introduced the better handling of uncaught exceptions by providing an optional function for printing stack traces. The sys.excepthook can be set to match any exception in the module as long as it has a hook attribute.

# test.py
import sys

def excepthook(type, value, traceback):
    print("Unhandled exception:", type, value)
    # Call the default exception hook
    sys.\_\_excepthook\_\_(type, value, traceback)

sys.excepthook = excepthook

def test_exception_hook():
    throw_some_exception()
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How to silence exceptions?

A
  • Silence exceptions with pass, continue, or else
  • pass: Simply does nothing. It acts as a placeholder.
try:
    risky_operation()
except SomeSpecificException:
    pass
  • continue: This keyword is generally used in loops. It moves to the next iteration without executing the code that follows it within the block.
for item in my_list:
    try:
        perform_something(item)
    except ExceptionType:
        continue
  • else with try-except blocks: The else block after a try-except block will only be executed if no exceptions are raised within the try block
try:
    some_function()
except SpecificException:
    handle_specific_exception()
else:
    no_exception_raised()
How well did you know this?
1
Not at all
2
3
4
5
Perfectly