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)
#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;
}
#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;
}
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");
}
}
}
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")
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");
}
}
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.
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