PDI · Question #181
Given the following Apex statement: What occurs when more than one Account is returned by the SOQL query?
The correct answer is D. An unhandled exception is thrown and the code terminates. When a SOQL query assigned to a single SObject variable returns more than one record, an unhandled System.QueryException is thrown, which terminates the Apex code execution.
Question
Given the following Apex statement:
What occurs when more than one Account is returned by the SOQL query?
Options
- AThe query falls and an error Is written to the debug log.
- BThe variable, nvAccount, Is automatically cast to the List data type.
- CThe first Account returned Is assigned to myAccour.t.
- DAn unhandled exception is thrown and the code terminates.
How the community answered
(21 responses)- A5% (1)
- D95% (20)
Why each option
When a SOQL query assigned to a single SObject variable returns more than one record, an unhandled `System.QueryException` is thrown, which terminates the Apex code execution.
While an error occurs and is logged, the primary consequence is an immediate runtime `QueryException` that, if unhandled, stops the transaction, rather than just logging an error and continuing.
Apex is a strongly typed language, and a single SObject variable cannot be automatically cast or converted to a `List` data type when multiple records are returned.
Apex does not automatically assign the first record found when a query assigned to a single SObject variable returns multiple records; it strictly enforces the 'one record or zero records' expectation for single variable assignment.
In Apex, if a SOQL query is intended to return a single SObject (i.e., assigned to a non-List SObject variable) but retrieves more than one record, a `System.QueryException` is immediately thrown. If this exception is not caught by a `try-catch` block, the current transaction rolls back, and the code execution is terminated.
Concept tested: SOQL query exception handling (single SObject assignment)
Source: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_SOQL_sosl.htm
Topics
Community Discussion
No community discussion yet for this question.