Panic in Verilog

module panic_example;

  // In Verilog, we don't have a direct equivalent to Go's panic.
  // Instead, we can use system tasks to report fatal errors.

  initial begin
    // We'll use $fatal throughout this example to check for
    // unexpected errors. This is the only program on the
    // site designed to terminate execution abruptly.
    $fatal(1, "a problem");

    // A common use of $fatal is to abort if a condition
    // that shouldn't occur during normal operation is met.
    // Here's an example of terminating if we encounter an
    // unexpected error when trying to open a file.
    integer file_handle;
    file_handle = $fopen("/tmp/file", "w");
    if (file_handle == 0) begin
      $fatal(1, "Failed to open file");
    end
  end

endmodule

A $fatal system task in Verilog typically means something went unexpectedly wrong. Mostly we use it to fail fast on errors that shouldn’t occur during normal operation, or that we aren’t prepared to handle gracefully.

Running this program will cause it to terminate execution, print an error message, and exit with a non-zero status.

When the first $fatal in the initial block fires, the simulation exits without reaching the rest of the code. If you’d like to see the program try to open a file, comment the first $fatal out.

$ iverilog panic_example.v
$ ./a.out
FATAL: a problem
Time: 0  Scope: panic_example

Note that unlike some languages which use exceptions for handling of many errors, in Verilog it is idiomatic to use conditional statements and system tasks like $display for reporting non-fatal errors, and $fatal or $finish for terminating simulation on critical errors.

In hardware description languages like Verilog, the concept of “panicking” is less common as the language is used to describe hardware behavior rather than software execution flow. The $fatal system task is used here as an analogue to demonstrate similar functionality.