Warnings and Assertions: GLib Reference Manual

## Warnings and Assertions Warnings and Assertions — warnings and assertions to use in runtime code |

## Functions

void | g_print ()
GPrintFunc | g_set_print_handler ()
void | (*GPrintFunc) ()
void | g_printerr ()
GPrintFunc | g_set_printerr_handler ()
#define | g_return_if_fail()
#define | g_return_val_if_fail()
#define | g_return_if_reached
#define | g_return_val_if_reached()
#define | g_warn_if_fail()
#define | g_warn_if_reached
void | g_on_error_query ()
void | g_on_error_stack_trace ()
#define | G_BREAKPOINT

## Includes

    #include <glib.h>

## Description

GLib defines several warning functions and assertions which can be used to warn of programmer errors when calling functions, and print error messages from command line programs.

The `g_return_if_fail()`, `g_return_val_if_fail()`, `g_return_if_reached()` and `g_return_val_if_reached()` macros are intended as pre-condition assertions, to be used at the top of a public function to check that the function’s arguments are acceptable. Any failure of such a pre-condition assertion is considered a programming error on the part of the caller of the public API, and the program is considered to be in an undefined state afterwards. They are similar to the libc `assert()` function, but provide more context on failures.

For example:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    gboolean
    g_dtls_connection_shutdown (GDtlsConnection  *conn,
                                gboolean          shutdown_read,
                                gboolean          shutdown_write,
                                GCancellable     *cancellable,
                                GError          **error)
    {
      // local variable declarations

      g_return_val_if_fail (G_IS_DTLS_CONNECTION (conn), FALSE);
      g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), FALSE);
      g_return_val_if_fail (error == NULL || *error == NULL, FALSE);

      // function body

      return return_val;
    }

g_print() and `g_printerr()` are intended to be used for output from command line applications, since they output to standard output and standard error by default — whereas functions like `g_message()` and `g_log()` may be redirected to special purpose message windows, files, or the system journal.

If the console encoding is not UTF-8 (as specified by `g_get_console_charset()`) then these functions convert the message first. Any Unicode characters not defined by that charset are replaced by `'?'`. On Linux, `setlocale()` must be called early in `main()` to load the encoding. This behaviour can be changed by providing custom handlers to `g_set_print_handler()`, `g_set_printerr_handler()` and `g_log_set_handler()`.

## Functions

### g_print ()

    void
    g_print (const gchar *format,
             ...);

Outputs a formatted message via the print handler. The default print handler outputs the encoded message to stdout, without appending a trailing new-line character. Typically, `format` should end with its own new-line character.

g_print() should not be used from within libraries for debugging messages, since it may be redirected by applications to special purpose message windows or even files. Instead, libraries should use `g_log()`, `g_log_structured()`, or the convenience macros `g_message()`, `g_warning()` and `g_error()`.

#### Parameters

format | the message format. See the `printf()` documentation |
... | the parameters to insert into the format string |

### g_set_print_handler ()

    GPrintFunc
    g_set_print_handler (GPrintFunc func);

Sets the print handler to `func` , or resets it to the default GLib handler if `NULL`.

Any messages passed to `g_print()` will be output via the new handler. The default handler outputs the encoded message to stdout. By providing your own handler you can redirect the output, to a GTK widget or a log file for example.

Since 2.76 this functions always returns a valid GPrintFunc, and never returns `NULL`. If no custom print handler was set, it will return the GLib default print handler and that can be re-used to decorate its output and/or to write to stderr in all platforms. Before GLib 2.76, this was `NULL`.

#### Parameters

func | the new print handler or `NULL` to reset to the default. | [nullable]

#### Returns

the old print handler.

[not nullable]

### GPrintFunc ()

    void
    (*GPrintFunc) (const gchar *string);

Specifies the type of the print handler functions. These are called with the complete formatted string to output.

#### Parameters

string | the message to output |

### g_printerr ()

    void
    g_printerr (const gchar *format,
                ...);

Outputs a formatted message via the error message handler. The default handler outputs the encoded message to stderr, without appending a trailing new-line character. Typically, `format` should end with its own new-line character.

g_printerr() should not be used from within libraries. Instead `g_log()` or `g_log_structured()` should be used, or the convenience macros `g_message()`, `g_warning()` and `g_error()`.

#### Parameters

format | the message format. See the `printf()` documentation |
... | the parameters to insert into the format string |

### g_set_printerr_handler ()

    GPrintFunc
    g_set_printerr_handler (GPrintFunc func);

Sets the handler for printing error messages to `func` , or resets it to the default GLib handler if `NULL`.

Any messages passed to `g_printerr()` will be output via the new handler. The default handler outputs the encoded message to stderr. By providing your own handler you can redirect the output, to a GTK widget or a log file for example.

Since 2.76 this functions always returns a valid GPrintFunc, and never returns `NULL`. If no custom error print handler was set, it will return the GLib default error print handler and that can be re-used to decorate its output and/or to write to stderr in all platforms. Before GLib 2.76, this was `NULL`.

#### Parameters

func | he new error message handler or `NULL` to reset to the default. | [nullable]

#### Returns

the old error message handler.

[not nullable]

### g_return_if_fail()

    #define             g_return_if_fail(expr)

Verifies that the expression `expr` , usually representing a precondition, evaluates to `TRUE`. If the function returns a value, use `g_return_val_if_fail()` instead.

If `expr` evaluates to `FALSE`, the current function should be considered to have undefined behaviour (a programmer error). The only correct solution to such an error is to change the module that is calling the current function, so that it avoids this incorrect call.

To make this undefined behaviour visible, if `expr` evaluates to `FALSE`, the result is usually that a critical message is logged and the current function returns.

If `G_DISABLE_CHECKS` is defined then the check is not performed. You should therefore not depend on any side effects of `expr` .

To debug failure of a `g_return_if_fail()` check, run the code under a debugger with `G_DEBUG=fatal-criticals` or `G_DEBUG=fatal-warnings` defined in the environment (see Running GLib Applications):

    1
    G_DEBUG=fatal-warnings gdb ./my-program

Any unrelated failures can be skipped over in gdb using the `continue` command.

#### Parameters

expr | the expression to check |

### g_return_val_if_fail()

    #define             g_return_val_if_fail(expr,val)

Verifies that the expression `expr` , usually representing a precondition, evaluates to `TRUE`. If the function does not return a value, use `g_return_if_fail()` instead.

If `expr` evaluates to `FALSE`, the current function should be considered to have undefined behaviour (a programmer error). The only correct solution to such an error is to change the module that is calling the current function, so that it avoids this incorrect call.

To make this undefined behaviour visible, if `expr` evaluates to `FALSE`, the result is usually that a critical message is logged and `val` is returned from the current function.

If `G_DISABLE_CHECKS` is defined then the check is not performed. You should therefore not depend on any side effects of `expr` .

See `g_return_if_fail()` for guidance on how to debug failure of this check.

#### Parameters

expr | the expression to check |
val | the value to return from the current function if the expression is not true |

### g_return_if_reached

    #define             g_return_if_reached()

Logs a critical message and returns from the current function. This can only be used in functions which do not return a value.

See `g_return_if_fail()` for guidance on how to debug failure of this check.

### g_return_val_if_reached()

    #define             g_return_val_if_reached(val)

Logs a critical message and returns `val` .

See `g_return_if_fail()` for guidance on how to debug failure of this check.

#### Parameters

val | the value to return from the current function |

### g_warn_if_fail()

    #define             g_warn_if_fail(expr)

Logs a warning if the expression is not true.

#### Parameters

expr | the expression to check |

Since: 2.16

### g_warn_if_reached

    #define             g_warn_if_reached()

Logs a warning.

Since: 2.16

### g_on_error_query ()

    void
    g_on_error_query (const gchar *prg_name);

Prompts the user with `[E]xit, [H]alt, show [S]tack trace or [P]roceed`. This function is intended to be used for debugging use only. The following example shows how it can be used together with the `g_log()` functions.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    #include <glib.h>

    static void
    log_handler (const gchar   *log_domain,
                 GLogLevelFlags log_level,
                 const gchar   *message,
                 gpointer       user_data)
    {
      g_log_default_handler (log_domain, log_level, message, user_data);

      g_on_error_query (MY_PROGRAM_NAME);
    }

    int
    main (int argc, char *argv[])
    {
      g_log_set_handler (MY_LOG_DOMAIN,
                         G_LOG_LEVEL_WARNING |
                         G_LOG_LEVEL_ERROR |
                         G_LOG_LEVEL_CRITICAL,
                         log_handler,
                         NULL);
      ...

If "[E]xit" is selected, the application terminates with a call to _exit(0).

If "[S]tack" trace is selected, `g_on_error_stack_trace()` is called. This invokes gdb, which attaches to the current process and shows a stack trace. The prompt is then shown again.

If "[P]roceed" is selected, the function returns.

This function may cause different actions on non-UNIX platforms.

On Windows consider using the `G_DEBUGGER` environment variable (see Running GLib Applications) and calling `g_on_error_stack_trace()` instead.

#### Parameters

prg_name | the program name, needed by gdb for the "[S]tack trace" option. If `prg_name` is `NULL`, `g_get_prgname()` is called to get the program name (which will work correctly if `gdk_init()` or `gtk_init()` has been called) |

### g_on_error_stack_trace ()

    void
    g_on_error_stack_trace (const gchar *prg_name);

Invokes gdb, which attaches to the current process and shows a stack trace. Called by `g_on_error_query()` when the "[S]tack trace" option is selected. You can get the current process's program name with `g_get_prgname()`, assuming that you have called `gtk_init()` or `gdk_init()`.

This function may cause different actions on non-UNIX platforms.

When running on Windows, this function is *not* called by `g_on_error_query()`. If called directly, it will raise an exception, which will crash the program. If the `G_DEBUGGER` environment variable is set, a debugger will be invoked to attach and handle that exception (see Running GLib Applications).

#### Parameters

prg_name | the program name, needed by gdb for the "[S]tack trace" option |

### G_BREAKPOINT

    #  define G_BREAKPOINT()        G_STMT_START{ __asm__ __volatile__ ("int $03"); }G_STMT_END

Inserts a breakpoint instruction into the code.

On architectures which support it, this is implemented as a soft interrupt and on other architectures it raises a `SIGTRAP` signal.

`SIGTRAP` is used rather than `abort()` to allow breakpoints to be skipped past in a debugger if they are not the desired target of debugging.