Panic in Modelica

model PanicExample
  import Modelica.Utilities.Files;
  import Modelica.Utilities.Streams;

equation
  when initial() then
    // We'll use assert throughout this example to check for
    // unexpected errors. This is the only program designed
    // to deliberately fail an assertion.
    assert(false, "a problem");

    // A common use of assert is to abort if a function
    // returns an error value that we don't know how to
    // (or want to) handle. Here's an example of
    // asserting if we get an unexpected error when creating a new file.
    Files.createDirectory("tmp");
    (success,msg) = Files.createFile("tmp/file");
    assert(success, "Failed to create file: " + msg);
  end when;
end PanicExample;

In Modelica, we don’t have a direct equivalent to Go’s panic function. Instead, we use the assert function to check for unexpected conditions and abort the simulation if they occur.

Running this model will cause it to fail the assertion, print an error message, and stop the simulation.

Error: Assertion failed: a problem

When the first assertion fails, the simulation stops without reaching the rest of the code. If you’d like to see the program try to create a temp file, comment out the first assertion.

Note that unlike some languages which use exceptions for handling of many errors, in Modelica it is idiomatic to use boolean return values and error messages for error handling where possible.

In this example, we’ve used the Files.createFile function which returns a tuple containing a boolean success flag and an error message. We then use an assertion to check if the file creation was successful.

Remember that Modelica is primarily used for modeling and simulation of physical systems, so error handling and program flow control are somewhat different from general-purpose programming languages.