Panic in Crystal

# A `panic` in Crystal is typically raised using the `raise` keyword.
# It's used to indicate unexpected errors that shouldn't occur during
# normal operation, or that we aren't prepared to handle gracefully.

# We'll use raise throughout this site to check for unexpected errors.
# This is the only program on the site designed to raise an exception.

raise "a problem"

# A common use of raise is to abort if a method returns an error value
# that we don't know how to (or want to) handle. Here's an example of
# raising an exception if we get an unexpected error when creating a new file.

begin
  File.new("/tmp/file", "w")
rescue ex
  raise ex
end

Running this program will cause it to raise an exception, print an error message and stack trace, and exit with a non-zero status.

When the first raise is executed, the program exits 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 raise.

$ crystal run panic.cr
Unhandled exception: a problem (Exception)
  from panic.cr:8:1 in __crystal_main
  from /usr/share/crystal/src/crystal/main.cr:109:5 in main
  from /usr/share/crystal/src/crystal/main.cr:135:7 in main

Note that unlike some languages which use exceptions for handling of many errors, in Crystal it is idiomatic to use error-indicating return values (like nil or a Result type) wherever possible, reserving exceptions for truly exceptional circumstances.