Error Handling
Error handling refers to the response and recovery procedures from error conditions present in a software application. In other words, it is the process comprised of anticipation, detection and resolution of application errors, programming errors or communication errors.
Note: Some languages like Julia handle infinity in their mathematical operations
Let's handle error for a program whereby there's division operation, and only constrains the denominator to non-zero.
go
js
dart
python
julia
package main

import (
    "errors"
    "fmt"
)

func divFun(num, den int) (int, error) {
    if den == 0 {
        return 0, errors.New("Cannot divide by 0")
    }
    return num / den, nil
}
func main() {
    res, err := divFun(12, 2)
    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Println("Result is", res)
    }
}
function divide(num: number, den: number, dp: number) {
    try {
        if (den == 0) throw new Error('Cannot divide by 0')
        return (num / den).toFixed(dp);
    }
    catch(e) {
        console.log(`
        error name   : ${ e.name }
        error message: ${ e.message }
        `)
        return 'ERROR';
    }
}

let a = 5,
    b = 3,
    c = 3;

let res = divide(a, b, c)
console.log(`${a} / ${b} to ${c}-float precision = ${res}`)
void main() {
    try {
        var res = divide(5, 4);
        print("Result : $res");
    } catch (e) {
        print(e);
    }
}

double divide(int num, int den) {
    if (den == 0) {
        throw "Cannot divide by 0";
    }
    return num / den;
}
def divide(num: int, den: int) -> float:
    if den == 0:
        raise Exception("Cannot divide by 0")
    return num / den
    
try:
    a , b = 5, 0 
    c = divide(a, b)
    print(f"The result is {c}")
except Exception as error:
    print(error)
function divide(num::Int64, den::Int64)::Float64
    if den == 0
        error("Cannot divide $num by 0")
    end
    return num / den
end

try
    res = divide(5, 3)
    println("The result is $res")
catch e
    println(e.msg)
end
Implementing Custom Errors
Custom errors are implemented and inherit from Error to customize the error handling flow
go
js
dart
python
julia
package main

import "fmt"

type DivideError float64

func (e DivideError) Error() string {
    // not casting e to int causes error call loop
    return fmt.Sprintf("Cannot divide %d by 0", int(e))
}

func divFun(num, den int) (int, error) {
    if den == 0 {
        e := DivideError(num)
        return 0, e
    }
    return num / den, nil
}

func main() {
    res, err := divFun(8, 0)
    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Printf("Res :: %d\n", res)
    }
}
class DivideError extends Error {
    constructor(message: string, num: number) {
        super(message); // (1)
        this.name = "DivideByZeroError"; // (2)
        this.message = `Cannot divide ${num} by zero`
    }
}

function divide(num: number, den: number, dp: number) {
    try {
        if (den == 0) throw new DivideError('Cannot divide by 0', num)
        return (num / den).toFixed(dp);
    }
    catch(e: any) {
        console.log(`
        error name   : ${ e.name }
        error message: ${ e.message }
        `)
        return 'ERROR';
    }
}
void main() {
    try {
        var res = divide(5, 0);
        print("Result : $res");
        } catch (e) {
            print(e);
    }
}

class DivideException implements Exception {
    final String? msg;
    const DivideException([this.msg]);

    @override
        String toString() => msg ?? 'DivideException';
}

double divide(int num, int den) {
    if (den == 0) {
        throw DivideException("Cannot divide $num by 0");
    }
    return num / den;
}
class DivideException(Exception):
    def __init__(self, num):
        self.message = f"Cannot divide {num} by 0"
        super().__init__(self.message)
        
    
def divide(num: int, den: int) -> float:
    if den == 0:
        raise DivideException(num)
    return num / den
    
try:
    a , b = 5, 0
    c = divide(a, b)
    print(f"The result is {c}")
except Exception as error:
    print(error)
using Base

struct DivideException <: Exception                                         
    msg::String                    
end

Base.showerror(io::IO, e::DivideException) = print(io, "DivideByZero: ", e.msg)

function divide(num::Int64, den::Int64)::Float64
    if den == 0
        throw(DivideException("Cannot divide $num by 0"))
    end
    return num / den
end

try
    res = divide(5, 3)
    println("The result is $res")
catch e
    error = sprint(showerror, e, catch_backtrace())
    print(error)
    #=
    OR

    for (exc, bt) in Base.catch_stack()
        showerror(stdout, exc, bt)
        println()
    end
    =#
end