Exceptions
- C
- C++
- C#
- Java
- Rust
- Go
- Javascript
- Typescript
- Python
// Not Available Natively
More Info:
// ------------------------------------
// Handling Exceptions
// ------------------------------------
// C++ Has no "Finally()"
try
{
// ...
}
catch(your_specific_exception& error) // Needs to be a Reference ( & ) so you dont break the Polymorphism
{
std::cout << "Specific excetion happened: " << error.what() << std::endl;
}
catch(exception& error)
{
std::cout << "An Excetion happened: " << error.what() << std::endl;
}
catch (...) // catch-all handler (Yes, ellipses)
{
// Often, the catch-all handler block is left empty
std::cout << "We caught an exception of an undetermined type\n";
}
// ------------------------------------
// Custom Exception
// ------------------------------------
class MyException : public std::exception
{
public:
const char* what() const noexcept override
{
return "Something went wrong";
}
};
throw MyException();
More Info:
// ------------------------------------
// Handling Exceptions
// ------------------------------------
try
{
// ...
}
catch(your_specific_exception error)
{
Console.WriteLine($"Specific excetion happened: {error}");
}
catch(your_specific_exception error) when (error.ParamName == "something") // Exception filter
{
Console.WriteLine($"Specific excetion happened: {error}");
}
catch(Exception error)
{
std::cout << "An Excetion happened: " << error.what() << std::endl;
}
finally // Optional
{
// This block will run for success or catch
// Ex.: need to close connection to a server
}
// ------------------------------------
// Custom Exception
// ------------------------------------
public class MyException : Exception
{
public MyException()
{
}
public MyException(string message) : base(message)
{
}
public MyException(string message, Exception innerException) : base(message, innerException)
{
}
}
throw new MyException("Something went wrong");
More Info:
// ------------------------------------
// Handling Exceptions
// ------------------------------------
try {
// ...
}
catch (YourSpecificException error) {
// ...
}
catch (Exception error) {
// ...
}
finally {
// This block will run for success or catch
}
// ------------------------------------
// Custom Exception
// ------------------------------------
class MyException extends Exception {
public MyException(String message) {
super(message);
}
}
throw new MyException("Something went wrong");
// Rust does not use exceptions for recoverable errors.
// Use Result<T, E>.
fn divide(first: i32, second: i32) -> Result<i32, String> {
if second == 0 {
return Err(String::from("division by zero"));
}
Ok(first / second)
}
match divide(10, 2) {
Ok(value) => println!("{}", value),
Err(error) => println!("{}", error),
}
// Panic is available for unrecoverable errors.
panic!("Something went wrong");
// Go does not use exceptions.
// Return errors as values.
func divide(first int, second int) (int, error) {
if second == 0 {
return 0, errors.New("division by zero")
}
return first / second, nil
}
value, err := divide(10, 2)
if err != nil {
return err
}
// panic/recover exists, but is usually reserved for unrecoverable errors.
// ------------------------------------
// Handling Exceptions
// ------------------------------------
// Javascript can only have 1 catch, so you need to use conditional inside
try {
// ...
}
catch(error) {
if (error instanceof TypeError) {
// statements to handle TypeError exceptions
}
else if (error instanceof RangeError) {
// statements to handle RangeError exceptions
}
else if (error instanceof EvalError) {
// statements to handle EvalError exceptions
}
else {
// ...
}
}
finally {
// Block of code to be executed regardless of the try / catch result
}
// ------------------------------------
// Custom Exception
// ------------------------------------
class MyError extends Error {
constructor(message) {
super(message);
this.name = "MyError";
}
}
throw new MyError("Something went wrong");
More Info:
// ------------------------------------
// Handling Exceptions
// ------------------------------------
// Typescipt does NOT allow type annotation on catch.
// https://github.com/Microsoft/TypeScript/issues/20024
try {
// ...
}
catch(error) {
if (error instanceof TypeError) {
// statements to handle TypeError exceptions
}
else if (error instanceof RangeError) {
// statements to handle RangeError exceptions
}
else if (error instanceof EvalError) {
// statements to handle EvalError exceptions
}
else {
// ...
}
}
finally {
// Block of code to be executed regardless of the try / catch result
}
// ------------------------------------
// Custom Exception
// ------------------------------------
class MyError extends Error {
public constructor(message: string) {
super(message);
this.name = "MyError";
}
}
throw new MyError("Something went wrong");
More Info:
# ------------------------------------
# Handling Exceptions
# ------------------------------------
try:
# ...
except YourSpecificError:
# ...
except YourSecondSpecificError as error:
print(f'YourSecondSpecificError: {error}')
except (RuntimeError, TypeError, NameError): # Multiple exceptions as a parenthesized tuple
pass # you can pass (do nothing)
except:
# The last except clause may omit the exception name(s), to serve as a wildcard.
# Use this with extreme caution, since it is easy to mask a real programming error in this way!
else: # Optional
# ...
finally: # Optional
# Executed under all circumstances.
# Example from the documentation
def divide(x, y):
try:
result = x / y # Variable Hoisted (See below)
except ZeroDivisionError:
print("division by zero!")
else:
print("result is", result)
finally:
print("executing finally clause")
# In Python if you declare a variable in a block scope (if statement, for statement, ...)
# the variable is hoisted to the outer function scope.
# ------------------------------------
# Custom Exception
# ------------------------------------
class MyError(Exception):
pass
raise MyError("Something went wrong")
More Info: