Exam2021_01 Flashcards
my_arr is reshaped to have 3 columns, and the number of rows is inferred automatically by numpy (using -1).
The shape of my_arr would be (2, 3) because the original array has 6 elements, and reshaping it to have 3 columns results in 2 rows.
The reshaped array would look like this:
[[0 1 2]
[3 4 5]]
The line my_arr[0] would select the first 2D array (of shape (4, 5)) from the 3D numpy array my_arr.
The line my_arr[0, 0] would select the first 1D array (of shape (3,)) from the 3D numpy array my_arr.
The AttributeError is raised but not caught by the except block because the except block is only looking for a ValueError. The finally block executes regardless of whether an exception was raised or not, and after the finally block executes, the AttributeError will propagate up the call stack.
So, the output will be:
done
And then the AttributeError will be raised.
D is correct
The key point is that once an exception is caught in an except block, it stops propagating unless you explicitly re-raise it (using the raise
statement). In this code, the except block just prints a message and doesn’t re-raise the error, so the exception is fully handled at that point.
If you wanted the ValueError to continue propagating, you would need to add a raise
statement in the except block, like this:
try: a_function() except ValueError: print("there was an exception!") raise # This would make the error continue propagating finally: print("done!")
Code Explanation:
- The code enters the
try
block -
a_function()
is called and raises a ValueError - Because ValueError was raised, execution jumps to the matching
except ValueError
block - The except block prints “there was an exception!” and handles the error (essentially catching and stopping it from propagating further)
- After either the try block completes successfully OR an exception is handled, the
finally
block always executes - The finally block prints “done!”
- The code continues normal execution because the exception was handled