Programming Languages - Error Handling
By Language
C++
In C and similar languages, it is common for functions to return values like -1, null, or the empty string to signal errors or missing results. This is known as in-band error handling.
In C, a write error is signaled by a negative count with the error code secreted away in a volatile location. In Go, Write can return a count and an error.
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
Java has both checked (compile-time errors) and unchecked exceptions (runtime errors).
Checked exceptions must be explicitly caught or declared by the developers to be thrown or instantly fixed.
try {
// ...
} catch(Exception e) {
// ...
} finally {
// ...
}
Throw:
throw new RuntimeException("Something is wrong.");
Kotlin
Kotlin does not have checked exceptions
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
Python does not distinguish between checked and unchecked exceptions.
Throw
raise ValueError('some error message')
Catch
try:
code_that_may_raise_exception()
except ValueError as err:
print(err.args)