anion
anion

Reputation: 2090

How can i throw an exception in Q#?

I try to write an algorithm in Q#. In some cases the algorithm can not calculate a result with success because the user passed some bad arguments. In this case i want to throw an exception and now i wonder: Is it possible to throw and catch exceptions in Q#?

If yes: how can i do that and what is the proper way of exception-handling in Q#?

If no: why? are there any workarounds?

Upvotes: 5

Views: 275

Answers (1)

Chris Granade
Chris Granade

Reputation: 933

Many of the cases in which catch clauses are especially helpful in general-purpose languages look somewhat like handling I/O errors, in that they are very difficult to predict and deal with through ordinary flow control. By contrast, Q# programs are intended to be predictable in their execution so that functors like Adjoint and Controlled can generate appropriate transformations of programs as part of larger quantum algorithms.

That said, as you point out, there are times where one cannot sensibly proceed from some condition. Thus, Q# provides a fail statement that operates similarly to a throw statement (but takes a String rather than an exception object), but does not provide an analogue to a trycatch block. The fail statement is intended to communicate to the C# host program that a Q# program cannot sensibly proceed, and is useful for cases such as when a user passes bad instance. For instance, this is used throughout the Facts.qs file in the standard libraries to implement classical assertion functions such as EqualityWithinToleranceFact:

function EqualityWithinToleranceFact(actual : Double, expected : Double, tolerance : Double) : Unit {
    let delta = actual - expected;
    if (delta > tolerance or delta < -tolerance) {
        fail $"Fact was false. Expected: '{expected}'. Actual: '{actual}'";
    }
}

Upvotes: 3

Related Questions