- Published on
Exception Handling in Multiple Languages
- Authors
- Name
- Nali Thephavong Haehn
In the past, I've been guilty of using exception handling to avoid addressing the underlying error, but after years of writing code I've realized my past self wasn't entirely wrong. Exception handling plays a vital role in managing errors and mitigating unpredictable code behavior. As a developer, incorporating a consistent exception handling strategy in your work not only reduces crashes, but also enforces good coding habits that your peers (and your future self) will likely appreciate.
Let's Talk Code
This isn't a food blog, so I won't be telling you the roundabout way I came to embrace exception handling, but I would like to point out a few things:
- Keep your code clean and readable:
finally
/ensure
is optional, remove it if you don't use it. - If you do decide to use
finally
/ensure
, pay attention to code flow. Don't return any values in the code block and only use it to clean up code. - The examples below are fairly basic, but you can do some fancy things with specific/custom exceptions handling utilizing multiple
catch
/except
/rescue
clauses. Ruby also has an optionalelse
switch that can be executed if no exceptions are raised, not to be confused withensure
which executes regardless of whether an exception was raised or not.
Some Javascript code:
let num1 = 5;
let num2 = 6;
try {
let sum = num1 + num2;
console.log(`Sum = ${sum}`);
} catch (err) {
if (!(err instanceof Error)) {
err = new Error(err);
}
console.error(`Uh oh: ${err.message}`);
} finally {
// optional code to execute after try/catch
// should not contain any returns, only for code cleanup
}
Some Typescript code:
let num1: number = 5;
let num2: number = 6;
try {
let sum: number = num1 + num2;
console.log(`Sum = ${sum}`);
} catch (err: unknown) {
console.error(`Uh oh: ${(err as Error).message}`);
} finally {
// optional code to execute after try/catch
// should not contain any returns, only for code cleanup
}
Some Python code 🐍:
try:
num1 = 5
num2 = 6
sum = num1 + num2
print(f"Sum = {sum}")
except Exception as ex:
print(f"Uh oh: {ex}")
finally:
# optional code to execute after try/except
Some Ruby code:
begin
a = 5
b = 6
sum = a + b
puts "Sum = #{sum}"
rescue StandardError => err
puts "Uh oh: #{err}"
ensure
# optional code to execute after begin/rescue
end
Some C# code:
int num1 = 5;
int num2 = 6;
try
{
int result = num1 + num2;
Console.WriteLine($"Sum = {result}");
}
catch (Exception e)
{
Console.WriteLine($"Uh oh: {e.Message}");
}
finally
{
// optional code to execute after try/catch
// should not contain any returns, only for code cleanup
}