logo

Polyglot CheatSheet - Error Handling

Last Updated: 2023-03-01

C++

C++ does have exceptions, however Google C++ Style Guide does not allow exceptions. (https://google.github.io/styleguide/cppguide.html#Exceptions)

try {
  // ...
} catch(string &err) {
  // ...
}

No finally block.

Java

try {
  // ...
} catch(Exception e) {
  // ...
} finally {
  // ...
}

Throw:

throw new RuntimeException("Something is wrong.");

Go

The error built-in interface:

type error interface {
    Error() string
}

Pattern:

// Define your own error.
type MyError struct {
	When time.Time
	What string
}

// Implement the `error` interface.
func (e *MyError) Error() string {
	return fmt.Sprintf("at %v, %s",
		e.When, e.What)
}


// Your func signature should return an `error`
func foo() error {
  // If something happens, return `MyError`:
  return &MyError{
		time.Now(),
		"it didn't work",
	}
}

// Catch and deal with the error.
if err := foo(); err != nil {
  // ...
}

Do not use panic for normal error handling.

Within package main and initialization code, consider log.Exit for errors that should terminate the program.s

Rust

Rust does not allow throwing exceptions, instead Rust handles errors through its return type.

match safe_div(1.0, 0.0) {
    Ok(v) => { println!("{}", v); },
    Err(err) => { println!("{}", err); }
}

Python

Throw

raise ValueError('some error message')

Catch

try:
    code_that_may_raise_exception()
except ValueError as err:
    print(err.args)

Ruby

  • begin/end
  • rescue keyword
  • ensure
  • raise