Panic in C#

using System;
using System.IO;

class Program
{
    static void Main()
    {
        // We'll use exceptions throughout this site to check for
        // unexpected errors. This is the only program on the
        // site designed to throw an exception.
        throw new Exception("a problem");

        // A common use of exceptions is to abort if a function
        // returns an error that we don't know how to
        // (or want to) handle. Here's an example of
        // throwing an exception if we get an unexpected error when creating a new file.
        try
        {
            using (FileStream fs = File.Create(@"C:\temp\file"))
            {
                // File created successfully
            }
        }
        catch (Exception ex)
        {
            throw new Exception("Error creating file", ex);
        }
    }
}

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

When the first exception in Main is thrown, 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 exception.

$ dotnet run
Unhandled exception. System.Exception: a problem
   at Program.Main() in /path/to/Program.cs:line 10

Note that unlike some languages which use return codes for handling of many errors, in C# it is idiomatic to use exceptions for exceptional circumstances and error-indicating return values (like bool or Result<T> types) for expected failure cases.

In C#, exceptions provide a structured way to handle errors and unexpected conditions. They allow you to separate error-handling code from your regular code, making your programs cleaner and more maintainable. When an exception is thrown, the runtime looks for the nearest catch block that can handle the exception. If no appropriate catch block is found in the current method, the exception “bubbles up” to the calling method, and so on up the call stack until it’s either caught or terminates the program.

Remember to use exceptions judiciously. They should be reserved for exceptional circumstances rather than for normal flow control. For expected error conditions, consider using return values or output parameters to indicate success or failure.