CodeBlanks Logo Icon CodeBlanks

Error and exit

Return a proper exit code on error.

Errors and exit

A good CLI writes error messages to stderr and returns a non-zero exit code, so scripts can detect failure. main can return an ExitCode:

use std::process::ExitCode;

fn main() -> ExitCode {
    let args: Vec<String> = std::env::args().collect();
    match calistir(&args) {
        Ok(mesaj) => {
            println!("{mesaj}");
            ExitCode::SUCCESS
        }
        Err(e) => {
            eprintln!("hata: {e}");
            ExitCode::from(1)
        }
    }
}

stdout and stderr

println! writes to standard output, eprintln! to standard error. When the user redirects output to a file (not liste > notlar.txt), error messages don't mix into the file and stay on screen. Exit code convention: 0 success, 1 general error, 2 incorrect usage.

fn cikis_kodu(r: &Result<String, String>) -> u8 {
    match r {
        Ok(_) => 0,
        Err(_) => 1,
    }
}

Practice Exit codes

Write fn cikis_kodu(r: &Result<String, String>) -> u8. Let main return ExitCode: print the codes for Ok("tamam") and Err("hata") separated by a space, then return ExitCode::SUCCESS.

Starter code

main.rs
fn main() {
    // buraya yaz
}

Sample solution

main.rs
use std::process::ExitCode;

fn cikis_kodu(r: &Result<String, String>) -> u8 {
    match r {
        Ok(_) => 0,
        Err(_) => 1,
    }
}

fn main() -> ExitCode {
    let a: Result<String, String> = Ok(String::from("tamam"));
    let b: Result<String, String> = Err(String::from("hata"));
    println!("{} {}", cikis_kodu(&a), cikis_kodu(&b));
    ExitCode::SUCCESS
}

Expected output

0 1

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Why is returning <code>ExitCode</code> from <code>main</code> preferred over <code>std::process::exit(1)</code>?

  • exit doesn't compile
  • ExitCode is smaller
  • No difference
  • exit terminates immediately and the drops of values on the stack don't run Correct answer

Explanation: A normal return lets cleanups like flushing buffers and closing files happen.

2 Error stream

Question
Err(e) => {
    ____!("hata: {e}");
    ExitCode::from(1)
}
Answer
Err(e) => {
    eprintln!("hata: {e}");
    ExitCode::from(1)
}

Explanation: eprintln! writes the message to standard error.

3 Concept and meaning

Term Meaning
ExitCode::SUCCESS 0
ExitCode::from(2) Incorrect usage
eprintln! stderr
println! stdout

All lessons in Intermediate