Handling errors and exceptions
C++
C#
Dart
F#
Go
JavaScript
Kotlin
Python
C++
#include <iostream>
#include <vector>
int main()
{
try
{
std::vector<int> numbers{};
// the vector::at() function throws an exception of type std::out_of_range
std::cout << numbers.at(10) << std::endl;
}
catch (const std::exception& err)
{
std::cerr << err.what() << std::endl;
}
std::cout << "End" << std::endl;
}
C#
try
{
List<int> numbers = new();
// Accessing index numbers[10] throws an IndexOutOfRange exception
Console.WriteLine(numbers[10]);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
finally {
Console.WriteLine("End");
}
Dart
void main() {
try {
var numbers = [];
// generates a RangeError
print(numbers[10]);
}
on Error catch(err) {
print(err);
}
print("End");
}
F#
try
let numbers: int list = []
// Accessing index numbers[10] throws an IndexOutOfRange exception
printfn "%d" numbers[10]
with
| e -> printfn "%s" e.Message
printfn "End"
In F#, try..with can return a default value if an error occurs:
let numbers: int list = []
let result =
try
// Accessing index numbers[10] throws an exception
numbers[10]
with
| _ -> 22
printfn "%d" result
Go
package main
import "fmt"
func work() {
// error handling
defer func() {
if r := recover(); r != nil {
fmt.Println(r)
}
}()
numbers := []int{}
fmt.Println(numbers[10])
}
func main() {
// actions where an error occurs are moved to a separate function
work()
fmt.Println("End")
}
JavaScript
try
{
// accessing an undeclared variable throws a ReferenceError exception
console.log(numbers[10]);
}
catch (e)
{
console.error(e);
}
finally {
console.log("End");
}
Kotlin
fun main() {
try {
var numbers = listOf<Int>();
// Accessing index numbers[10] throws an ArrayIndexOutOfBoundsException
println(numbers[10]);
}
catch (e: Exception) {
println(e.message);
}
finally {
println("End");
}
}
In Kotlin, try..catch can also return a default value:
fun main() {
var numbers = listOf<Int>();
val result = try {
numbers[10] // return the list element
}
catch (e: Exception) {
println(e.message);
22 // default value
}
println(result) // 22
}
Python
numbers = []
try:
# Accessing index numbers[10] throws an IndexError exception
print(numbers[10])
except BaseException as e:
print(e)
finally:
print("End")
Next