What exit code does an uncaught Exception with no exit code give, and what about one that wraps a cause?

← Error Handling and Exceptions · Ref: Q1433

An uncaught Exception with no exit code ends the program with status 1. Only the exception that reaches the top counts. A wrapping exception does NOT inherit its cause's code, even when the cause has one.

In the program below, connect() throws Exception(... , 4). startService() catches it and throws a new Exception("Service failed to start", ex) with no code of its own. The process exits 1, not 4. The cause still appears in the stderr line: 'Exception in thread "main" Exception: Service failed to start: Root Cause: Exception: Cannot reach db.example.com: Exit Code: 4'. The 'Exit Code: 4' in that line belongs to the cause. The status is 1.

TO KEEP A CODE WHEN WRAPPING

Give the wrapper its own code: Exception("Service failed to start", ex, 4) exits 4. The code is chosen by whoever throws last, because only that code describes the failure the program is reporting.

See Q1432 for an exception that carries its code. See Q1436 for catching and throwing again. See Q1431 for every way a program sets its exit status.

Example

defines module qa.errorhandling.uncaughtnocode

  defines function

    connect()
      -> host as String
      throw Exception(`Cannot reach ${host}`, 4)

    startService()
      try
        connect("db.example.com")
      catch
        -> ex as Exception
        throw Exception("Service failed to start", ex)

  defines program

    UncaughtNoCodeDemo()
      stdout <- Stdout()
      stdout.println("Starting service")
      startService()
Other ways to ask this
  • Why did my program exit 1 when the inner exception had code 4?
  • Does a wrapping exception inherit its cause's exit code?
  • What is the default exit code of an uncaught Exception?

Coming from another language?

Java: every uncaught exception exits 1. Python: an uncaught exception exits 1. EK9: an uncaught Exception exits with its OWN exit code, or 1 when it has none. A cause's code is never used.

Keywords: cause, exception chaining, exit code, uncaught, default, wrap, root cause