# `JSON_THROW_ON_ERROR`

> Section in “New and Extended Functionality › Error Handling” of the book [PHP 7 Explained](https://php7explained.com/) by Sebastian Bergmann and Stefan Priebsch, published by thePHP.cc. The book covers PHP 7.0 to 7.4 and was last updated in November 2020. HTML version: <https://php7explained.com/new-and-extended-functionality/error-handling/json_throw_on_error/>

When something goes wrong, the `json_encode()` function returns `false` by default:

``` php
var_dump(json_encode('\x80'));
```

Executing the code shown above will print the output shown below:

    bool(false)

This is not very helpful and to make things worse, if you want to know what went wrong, you have to call `json_last_error()` which returns an error code. And then you need to know what that error code means.

To make all of this easier, PHP 7.3 introduced the `JSON_THROW_ON_ERROR` option:

``` php
try {
    $json = json_encode('\x80', JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
    print $e->getMessage();
}
```

Executing the code shown above will print the output shown below:

    Malformed UTF-8 characters, possibly incorrectly encoded

By default, the `json_decode()` function handles errors similarly to `json_encode()` – with the difference that it returns `NULL` when something goes wrong:

``` php
var_dump(json_decode('{'));
```

Executing the code shown above will print the output shown below:

    NULL

The `JSON_THROW_ON_ERROR` option can be used with `json_decode()`, too:

``` php
try {
    $variable = json_decode('{', false, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
    print $e->getMessage();
}
```

Executing the code shown above will print the output shown below:

    Syntax error

---

Previous: [Stack Traces and Arguments](https://php7explained.com/new-and-extended-functionality/error-handling/stack-traces-and-arguments/index.html.md) | Next: [Handling Multiple Exception Types with one catch Statement](https://php7explained.com/new-and-extended-functionality/error-handling/handling-multiple-exception-types-with-one-catch-statement/index.html.md)
