# throw

> Raises a fault. It ends the function immediately, and the rows the function wrote are discarded rather than half-written. The exception types are a closed set you do not add to — usable as ordinary types too, so a variable, a field or a parameter can hold one. CATCHING one is different: the refused row stays staged, and the catch has to say what happens to it.

<!-- id: function-throw · area: function · stability: stable · html: https://osysharp.com/reference/function/throw/ -->

## Summary        {#summary}
`throw` raises a fault. The function stops where it stands, and **the rows it wrote are discarded** — a function that
throws leaves nothing half-written behind it.

You throw one of a **closed set of types**. There is no `class MyException` to declare:

```osy title="refuse, and say why" test app=function-throw
entity Order {
  [Required, Unique, MaxLength(20)] string Code;
  decimal Total;

  // Every entity states who may touch it — with no `security { }` block it is denied to everyone.
  // A real app scopes these grants to a user; an example still has to declare them, because an example
  // that could not actually run is not an example. See the security guide.
  security { allow create, read, update when IsAuthenticated || IsAnonymous; }
}

void Refund(string code, decimal amount) {
  var order = Order.SingleOrDefault(o => o.Code == code);
  if (order == null) { throw new NotFoundException($"no order '{code}'"); }
  if (amount > order.Total) { throw new ValidationException("a refund cannot exceed the order total"); }

  order.Total = order.Total - amount;
}
```

## Signature      {#signature}
```osy syntax
throw new Exception("<message>");                  // the base type — the catch-all
throw new NotFoundException("<message>");          // asked for a thing that is not there
throw new ValidationException("<message>");        // the input or the resulting row is not acceptable
throw new ConflictException("<message>");          // it clashes with the current state of the data
throw new OAuthConnectionFailedException("<msg>"); // an external authorization handshake failed
```

## Description    {#description}

### Which types are there?   {#the-types}
The vocabulary is closed. Naming an unknown type is a compile error that lists every one you may use **and what
raises it**, so you cannot misspell your way into a silent catch-all:

| Type | What it means | Also raised for you by |
|---|---|---|
| `Exception` | the base. Every other type is one, so `catch (Exception e)` catches everything | — |
| `NotFoundException` | you asked for something that does not exist | — |
| `ValidationException` | the input, or the row you are about to write, is not acceptable | a broken [[entity-constraints\|constraint]] or [[entity-invariants\|invariant]] — including a duplicate under `[Unique]` |
| `ConflictException` | it cannot be done given the current state of the data | two writers colliding — see [ConcurrencyCheck](https://osysharp.com/reference/entity/concurrency-check/) |
| `OAuthConnectionFailedException` | an external authorization handshake failed | the OAuth surface |
| `NotAuthorized` | the caller may not do this — and the one to throw when your own function refuses on authorization grounds | a workflow event's `[Authorize]`, or a slot's candidate gate |
| `RequirementsNotMet` | the WORK is not finished, which is not the same as not being allowed | a slot deposit whose `Requires` criteria are unmet |
| `DeviceUnavailableException` | the browser would not hand over a camera or microphone. `ex.Message` says which of the four reasons | `Camera.Start()` / `Mic.Start()` |
| `WorkflowError` | an awaited child workflow reached a `terminal error`. **Catch-only** — throwing it is refused | the engine |
| `WorkflowCancelled` | an awaited child workflow reached a `terminal cancel`. **Catch-only** — throwing it is refused | the engine |

The point of the closed set is that a `catch` has a **finite, knowable** set of things to match on, and every type
the platform raises on your behalf is in it. That is what lets you catch a constraint violation as an ordinary
`ValidationException` ([try / catch / finally](https://osysharp.com/reference/function/try-catch/)) rather than by inspecting a database error.

⚠ **`ValidationException` is the duplicate one, however much English disagrees.** A row refused by `[Unique]` is the
entity's own declared rule saying no, so it is a `ValidationException` — not a `ConflictException`, which is about
what the DATA currently says. The two catch differently and the English pulls the wrong way, which is why the
compile error that lists these names lists what raises each beside it.

### Holding one in a variable   {#as-a-type}
A fault type is an **ordinary type**: it may stand wherever a type name may, so a local, a field, a parameter, a
return type or a generic argument can hold one. Assignment follows the same rule a typed `catch` does — every
subtype widens to `Exception`, and nothing narrows back without you saying which you meant.

```osy title="hold the fault and act on it after the try" test app=function-throw-astype
string Latest(string code) {
  Exception? caught = null;
  try { throw new ConflictException($"'{code}' moved under you"); }
  catch (Exception e) { caught = e; }
  return caught == null ? "fine" : $"{caught.Type}: {caught.Message}";
}
```

### Catching a constraint violation is not the end of it   {#the-refused-row}
⚠ **The row the database refused is still there when your `catch` runs, and doing nothing about it is the one shape
that does not work.** This is the trap, because the code that falls into it is the code everybody writes first:

```osy title="the catch runs — and the 409 never reaches the caller" syntax
int Book(string code) {
  try {
    var b = new Order { Code = code, Total = 10m };
    return 201;
  } catch (ValidationException e) {
    return 409;              // ⛔ the catch DOES run. The refused Order is still staged, so the function
  }                          //    then faults at its own boundary with the same violation, after this
}                            //    `return` has already happened. The caller gets the platform's message.
```

Nothing is dropped for you, and that is deliberate: **it is your data.** A form that is still open on screen must be
able to take the 409, let the user change the value, and save again — so the platform holds the row and leaves the
decision to the app, because only the app knows whether its form closed as part of saving.

There are **three** things you can do about it, and which one is right is a question about your UI:

| Your form… | Do this | Why |
|---|---|---|
| **stays open** after a failed save | **amend the row** in the catch | the end settlement persists the repair — one write, the value the user fixed |
| **stays open**, and the app should say so in its own words | **`throw new ConflictException("…")`** | a throw discards ([[#rollback]]); your sentence reaches the caller and nothing is written |
| **closes** as part of save — there is nothing to get back to | **`UnitOfWork.Discard()`** first, then return | the row is gone, and the function returns your status code normally |

```osy title="all three, and each is a complete answer" test app=function-throw
// The form stays open: fix the value the user gave and let the settlement write it.
string AmendAndKeep(string code) {
  var o = new Order { Code = "provisional", Total = 10m };
  try {
    o.Code = code;
    return "written";
  } catch (ValidationException e) {
    o.Code = "provisional-2";
    return "amended";
  }
}

// Say it in the app's own words. Nothing is written.
string RefuseInMyOwnWords(string code) {
  try {
    var o = new Order { Code = code, Total = 10m };
    return "created";
  } catch (ValidationException e) {
    throw new ConflictException($"the code '{code}' is already spoken for");
  }
}

// The form closed on save. Decline the row explicitly, then answer for yourself.
int DeclineTheRow(string code) {
  try {
    var o = new Order { Code = code, Total = 10m };
    return 201;
  } catch (ValidationException e) {
    UnitOfWork.Discard();
    return 409;
  }
}
```

Proved, not asserted — the discard shape returns its own status code, and writes nothing:

```osy title="a declined row is gone, and the function returns normally" run app=function-throw
[Test]
void Discarding_in_the_catch_lets_the_function_answer_for_itself() {
  var tooLong = "0123456789012345678901234567890123456789";   // > MaxLength(20)

  Assert.Equal(409, DeclineTheRow(tooLong));   // the function's OWN status code, not the platform's fault
  Assert.Empty(Order.ToList());                // and nothing was written
}
```

⭐ **`osy lint` finds the fourth shape for you** — the catch that repairs nothing, rethrows nothing and discards
nothing — as `data-caught-write-fault-left-staged`, and its remedy names all three of the above.

**Why you cannot declare your own:** a fault's *type* is what a `catch` matches on, and its *message* is what a human
reads. A bespoke type would carry no more information than the message already does, and it would not survive leaving
the app — see below.

### A throw discards what the function wrote   {#rollback}
This is the part worth internalising. A function is transactional ([function](https://osysharp.com/reference/function/declaration/)), and a throw is the abort:

```osy title="the first row is not left behind" test app=function-throw
void PlaceTwo(string first, string second) {
  var a = new Order { Code = first, Total = 10m };

  if (second == "") { throw new ValidationException("the second code is required"); }

  var b = new Order { Code = second, Total = 20m };
}
```

If `second` is empty, **neither order exists.** The first `new Order` was already written in the ordinary sense — it is
simply never committed. You do not unwind it, and there is no state in which the caller can observe it.

Proved, not asserted:

```osy title="a fault leaves nothing behind" run app=function-throw
[Test]
void A_throw_discards_the_rows_the_function_had_written() {
  Assert.Throws<ValidationException>(() => PlaceTwo("A1", ""));

  Assert.Empty(Order.ToList());   // NOT one row — the first `new Order` went with it
}

[Test]
void The_type_is_what_a_caller_matches_on() {
  Assert.Throws<NotFoundException>(() => Refund("nope", 1m));
}
```

### `throw` ends a path   {#definite-return}
A `throw` satisfies the compiler's "all paths return a value" rule, exactly as it does in C#. A guard clause that
throws needs no `else`:

```osy title="a guard clause, with no else" test app=function-throw
decimal TotalOf(string code) {
  var order = Order.SingleOrDefault(o => o.Code == code);
  if (order == null) { throw new NotFoundException($"no order '{code}'"); }

  return order.Total;   // reachable only when the order exists — no `else`, no null check
}
```

### What a caller outside the app sees   {#the-boundary}
Inside the app, a throw is caught by type ([try / catch / finally](https://osysharp.com/reference/function/try-catch/)).

A function reached from **outside** the app — over its published REST surface, or as a tool call — is different: a
fault becomes a failure carrying **your message**, and **the type does not survive the crossing**. So write the
message for the person who will read it, and do not expect an external caller to branch on `NotFoundException` versus
`ValidationException`. Inside, the type is everything; at the edge, the message is.

## See also       {#see-also}
- [try / catch / finally](https://osysharp.com/reference/function/try-catch/) — catching one, and what else can throw
- [UnitOfWork](https://osysharp.com/reference/function/unit-of-work/) — `UnitOfWork.Discard()`, the third answer to a refused row
- [function](https://osysharp.com/reference/function/declaration/) — why a fault discards the writes: a function is one transaction
- [constraints](https://osysharp.com/reference/entity/constraints/) · [invariant](https://osysharp.com/reference/entity/invariants/) — the rules that raise `ValidationException` for you
- [Assert](https://osysharp.com/reference/testing/assert/) — `Assert.Throws<T>`, which is how you prove a function refuses what it should
