Exceptions & Errors#

https://static.javatpoint.com/core/images/types-of-exception-handling.png

Overview#

Definition

Exception handling is a mechanism in programming languages that deals with runtime errors and exceptional situations. It allows you to gracefully handle errors and continue execution rather than crashing the program.

Use Cases

Exception handling is used in scenarios where unexpected situations can arise, such as file I/O errors, network communication issues, or arithmetic errors.

Pros & Cons

👍
Readability

Improves code readability by separating error-handling logic from main program flow.

Structured

Provides a structured way to handle errors and recover gracefully.

Robust & Reliability

Enhances program robustness and reliability by preventing crashes due to unexpected errors.

👎
Overhead

Can introduce performance overhead when exceptions are thrown frequently.

Convoluted Code

Overuse of exceptions can lead to convoluted code and reduced maintainability.

Exception & Error Handling Syntax#

BEGIN
    TRY
        Read userInput
        Convert userInput to integer
        PRINT "You entered:", userInput
    CATCH InvalidInputException
        PRINT "Invalid input! Please enter a valid integer."
    CATCH Exception
        PRINT "An unexpected error occurred."
    END TRY
END

 1#include <iostream>
 2using namespace std;
 3
 4int main() {
 5    try {
 6        int userInput;
 7        cin >> userInput;
 8        if (cin.fail()) {
 9            throw runtime_error("Invalid input! Please enter a valid integer.");
10        }
11        cout << "You entered: " << userInput << endl;
12    }
13    catch (const exception &e) {
14        cerr << e.what() << endl;
15    }
16    return 0;
17}
 1def main():
 2    try:
 3        user_input = int(input("Enter an integer: "))
 4        print("You entered:", user_input)
 5    except ValueError:
 6        print("Invalid input! Please enter a valid integer.")
 7    except Exception as e:
 8        print("An unexpected error occurred.")
 9
10
11if __name__ == "__main__":
12    main()
 1import java.util.Scanner;
 2
 3public class ErrorHandlingDemo {
 4    public static void main(String[] args) {
 5        try {
 6            Scanner scanner = new Scanner(System.in);
 7            int userInput = scanner.nextInt();
 8            System.out.println("You entered: " + userInput);
 9        } catch (java.util.InputMismatchException e) {
10            System.err.println("Invalid input! Please enter a valid integer.");
11        } catch (Exception e) {
12            System.err.println("An unexpected error occurred.");
13        }
14    }
15}
 1use std::io;
 2
 3fn main() {
 4    let mut user_input = String::new();
 5    io::stdin().read_line(&mut user_input).expect("Failed to read input");
 6    match user_input.trim().parse::<i32>() {
 7        Ok(num) => println!("You entered: {}", num),
 8        Err(_) => println!("Invalid input! Please enter a valid integer."),
 9    }
10}
 1package main
 2
 3import (
 4	"fmt"
 5	"strconv"
 6)
 7
 8func main() {
 9	var userInput string
10	fmt.Print("Enter an integer: ")
11	fmt.Scan(&userInput)
12	num, err := strconv.Atoi(userInput)
13	if err == nil {
14		fmt.Println("You entered:", num)
15	} else {
16		fmt.Println("Invalid input! Please enter a valid integer.")
17	}
18}

Compare & Contrast#

Language

Methodology

Comments/Notes

C++

Exception-based with try and catch blocks

Utilizes standard exceptions for error handling.

Python

Exception-based using try and except clauses

Python’s concise syntax simplifies error handling.

Java

Exception-based with try, catch, and throw

Strongly typed exceptions offer clear error identification.

Rust

Result-based approach with Result and match

Forces explicit handling of success or error cases.

Go

Return value-based with error returns and if checks

Simplicity in error handling with multiple return values.