Try, Catch/ Except and Finally Blocks

Within the domain of programming languages, error handling commonly incorporates constructs such as ‘try’, ‘catch’ (or ‘except’), and ‘finally’ blocks. The ‘try’ block encapsulates the code where an error might occur, while the ‘catch’ (or ‘except’) block is responsible for capturing and handling the error. The optional ‘finally’ block ensures the execution of specific code, irrespective of whether an error occurs or not.

This arrangement allows programmers to adeptly navigate through errors, averting potential catastrophic crashes.

Example: (Zero Division Error)

C++
#include <iostream>
#include <stdexcept>
using namespace std;

int main() {
    int divisor = 0;

    try {
        // Code that might raise an error
        if (divisor == 0) {
            // This will throw a std::runtime_error
            throw runtime_error("Error: Division by zero");
        } else {
            // Code to be executed if no error occurs
            int result = 10 / divisor;
            cout << "Result: " << result << endl;
        }
    } catch (const std::runtime_error& e) {
        // Handle the error
        cerr << e.what() << endl;
    } catch (...) {
        // Handle other types of exceptions if needed
    }

    // Code to be executed regardless of whether an error occurred
    cout << "Finally block executed" << endl;

    return 0;
}
C
#include <stdio.h>

int main()
{
    int divisor = 0;

    // Code that might raise an error
    if (divisor == 0) {
        // Handle the error
        fprintf(stderr, "Division by zero!");
        exit(-1);
    }
    else {
        // Code to be executed if no error occurs
        int result = 10 / divisor;
        printf("Result: %d\n", result);
    }

    // Code to be executed regardless of whether an error
    // occurred
    printf("Finally block executed\n");
    exit(0);

    return 0;
}
Java
public class Main {
    public static void main(String[] args)
    {
        int divisor = 0;

        try {
            // Code that might raise an error
            if (divisor == 0) {
                // This will throw an ArithmeticException
                throw new ArithmeticException(
                    "Error: Division by zero");
            }
            else {
                // Code to be executed if no error occurs
                int result = 10 / divisor;
                System.out.println("Result: " + result);
            }
        }
        catch (ArithmeticException e) {
            // Handle the error
            System.err.println(e.getMessage());
        }
        catch (Exception e) {
            // Handle other types of exceptions if needed
        }
        finally {
            // Code to be executed regardless of whether an
            // error occurred
            System.out.println("Finally block executed");
        }
    }
}
Python
divisor = 0

try:
    # Code that might raise an error
    if divisor == 0:
        # This will raise a RuntimeError
        raise RuntimeError("Error: Division by zero")
    else:
        # Code to be executed if no error occurs
        result = 10 / divisor
        print("Result:", result)
except RuntimeError as e:
    # Handle the error
    print(str(e))
except:
    # Handle other types of exceptions if needed
    pass

# Code to be executed regardless of whether an error occurred
print("Finally block executed")
C#
using System;

class Program {
    static void Main(string[] args)
    {
        int divisor = 0;

        try {
            // Code that might raise an error
            if (divisor == 0) {
                // This will throw an exception
                throw new DivideByZeroException(
                    "Error: Division by zero");
            }
            else {
                // Code to be executed if no error occurs
                int result = 10 / divisor;
                Console.WriteLine("Result: " + result);
            }
        }
        catch (DivideByZeroException e) {
            // Handle the error
            Console.WriteLine(e.Message);
        }
        catch (Exception) {
            // Handle other types of exceptions if needed
        }

        // Code to be executed regardless of whether an
        // error occurred
        Console.WriteLine("Finally block executed");
    }
}
JavaScript
function main() {
    let divisor = 0;

    try {
        // Code that might raise an error
        if (divisor === 0) {
            // This will throw an Error object
            throw new Error("Error: Division by zero");
        } else {
            // Code to be executed if no error occurs
            let result = 10 / divisor;
            console.log("Result: " + result);
        }
    } catch (error) {
        // Handle the error
        console.error(error.message);
    } finally {
        // Code to be executed regardless of whether an error occurred
        console.log("Finally block executed");
    }
}

main();

Error Handling in Programming

In Programming, errors occur. Our code needs to be prepared for situations when unexpected input from users occurs, division by zero occurs, or a variable name is written incorrectly. To prevent unexpected events from crashing or having unexpected outcomes, error handling involves putting in place methods to identify, report, and manage problems.

Error Handling in Programming

Table of Content

  • What is Error Handling in Programming?
  • Try, Catch, Except, and Finally Blocks
  • Comparison between Try, Catch/ Except and Finally Blocks
  • Common Errors and Debugging
  • Debugging Techniques in Programming
  • Debugging Tools in Programming
  • Best Practices for Error Handling in Programming

Similar Reads

What is Error Handling in Programming?

Error handling in Programming is a fundamental aspect of programming that addresses the inevitable challenges associated with unexpected issues during code execution. These issues may range from simple typographical errors to more intricate runtime errors that manifest during the program’s operation. The effectiveness of error handling is crucial in the development of software that is not only functional but also resilient and dependable....

Try, Catch/ Except and Finally Blocks:

Within the domain of programming languages, error handling commonly incorporates constructs such as ‘try’, ‘catch’ (or ‘except’), and ‘finally’ blocks. The ‘try’ block encapsulates the code where an error might occur, while the ‘catch’ (or ‘except’) block is responsible for capturing and handling the error. The optional ‘finally’ block ensures the execution of specific code, irrespective of whether an error occurs or not....

Comparison Between Try, Catch/ Except and Finally Blocks:

BlockPurposeExecution FlowtryEncloses the code where an exception might occur.Code inside the try block is executed.catch/exceptCatches and handles exceptions raised in the try block.If an exception occurs in the try block, the corresponding catch/except block is executed.finallyContains code that will be executed regardless of whether an exception occurred or not.Executed after the try block, whether an exception occurred or not....

Common Errors and Debugging:

Understanding common errors is essential for proficient error handling. Syntax errors emerge during the compilation phase and are relatively easy to identify. In contrast, runtime errors manifest during program execution and can involve a wide range of issues, such as division by zero, file not found, or invalid input....

Debugging Techniques in Programming:

1. Breakpoints:...

Debugging Tools in Programming:

There are many tools available to help in debugging:...

Best Practices for Error Handling in Programming:

To enhance error handling, follow these best practices:...