Try Catch

When a runtime error or exception occurs, the program will terminate and generate an error message. This is not exactly ideal for the user. What would be better is if we could catch these errors and then do what is necessary to fix the problem. A common example is when we ask the user to enter a number, but for some reason they entered text. Ideally we would not want the program just to crash, we would want to explain to the user they entered something incorrectly.

To catch these runtime errors, a portion of code is enclosed in a try-catch block. When an exceptional circumstance arises within that block, an exception is thrown that transfers the control to the exception handler. If no exception is thrown, the code continues normally and all handlers are ignored. The try statement normally takes the generic form like:

TRY
some statement(s) to be performed, which may raise an exception
CATCH (type of error)
some statement(s) to be performed, if an exception is raised
ELSE
some statement(s) to be performed, if no exception is raised
FINALLY
some statement(s) to be performed, regardless of whether an exception is raised or not
ENDTRY

You can define as many exception blocks as you want (e.g. if you want to execute a special block of code for a special kind of error). You use the else keyword to define a block of code to be executed if no errors were raised (this is python only). The finally block, if specified, will be executed regardless if the try block raises an error or not.

In this example program, the user is asked to enter an integer. The program then tries to convert the entered string into an integer. If the program fails to convert the string to an integer, instead of crashing the program will warn the user. If it succeeds, the program will continue as normal. The program will also print a message at the end, regardless of whether an error was raised or not.

Top-Down Design for Try Catch statement

Top-Down Design for Try Catch statement

Flowchart for Try Catch statement

Try Catch flowchart

Pseudocode for Try Catch statement

GET integer_as_string
TRY
CONVERT integer_as_number = int(integer_as_string)
EXCEPT invalid_argument
SHOW “The error was …”
ELSE
SHOW “You entered: ” + integer_as_number
FINALLY
SHOW “Thanks for playing.”
ENDTRY

Code for Try Catch statement

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// Copyright (c) 2020 Mr. Coxall All rights reserved.
//
// Created by: Mr. Coxall
// Created on: Sep 2020
// This program checks for a runtime error

#include <stdio.h>

int main() {
    // this function checks for a runtime error
    int integerValue = 0;
    int scanErrorCode = 0;

    // input
    printf("Enter an integer: ");
    scanErrorCode = scanf("%d", &integerValue);

    // process and output
    if (scanErrorCode == 1) {
        printf("You entered: %d\n", integerValue);
    } else {
        printf("You did not enter an integer.\n");
    }
    printf("Thanks for playing.\n");

    printf("\nDone.\n");
    return 0;
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// Copyright (c) 2020 St. Mother Teresa HS All rights reserved.
//
// Created by: Mr. Coxall
// Created on: Sep 2020
// This program checks for a runtime error

#include <iostream>
#include <string>

int main() {
    // this function checks for a runtime error
    std::string integerAsString;

    // Input
    std::cout << "Enter an integer: ";
    getline(std::cin, integerAsString);

    // Process & Output
    try {
        int integerAsNumber = stoi(integerAsString);
        std::cout << "You entered: " << integerAsNumber << "." << std::endl;
    }
    catch (const std::invalid_argument &err) {
        std::cout << "The error was: " << err.what() << "." << std::endl;
    }
    std::cout << "Thanks for playing." << std::endl;

    std::cout << "\nDone." << std::endl;
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/* Created by: Mr. Coxall
 * Created on: Sep 2020
 * This program checks for a runtime error
*/

using System;

/*
 * The Program class
*/
class Program {
    static void Main() {
        // this function checks a student's grade

        // Input
        Console.Write("Enter an integer: ");
        string integerAsString = Console.ReadLine();

        // Process & Output
        try {
            int integerAsNumber = int.Parse(integerAsString);
            Console.WriteLine($"You entered: {integerAsNumber}.");
        } catch (FormatException e) {
            Console.WriteLine($"The error was: {e.Message}.");
        } finally {
            Console.WriteLine("Thanks for playing.");
        }

        Console.WriteLine("\nDone.");
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
 * Created by: Mr. Coxall
 * Created on: Sep 2020
 * This program checks for a runtime error
 */

package main

import (
	"fmt"
	"strconv"
)

func main() {
	// this function checks for a runtime error

	var integerAsString string

	// input
	fmt.Print("Enter an integer: ")
	fmt.Scanln(&integerAsString)

	// process and output
	integerAsNumber, err := strconv.Atoi(integerAsString)

	if err == nil {
		fmt.Println("You entered: ", integerAsNumber)
	} else {
		fmt.Println("The error was:", err, ".")
	}

	fmt.Println("Thanks for playing.")

	fmt.Println("\nDone.")
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/*
 * This program checks for a runtime error
 *
 * @author  Mr Coxall
 * @version 1.0
 * @since   2020-09-01
 */

import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    // this function checks for a runtime error

    // create Scanner object for user input
    Scanner scanner = new Scanner(System.in);

    // input
    System.out.print("Enter an integer: ");
    String integerAsString = scanner.nextLine();

    // process & output
    try {
      int integerAsNumber = Integer.parseInt(integerAsString);
      System.out.printf("You entered: %d.%n", integerAsNumber);
    } catch (NumberFormatException e) {
      System.out.printf("The error was: %s.%n", e.getMessage());
    } finally {
      System.out.println("Thanks for playing.");
    }

    // close the Scanner object
    scanner.close();
    System.out.println("\nDone.");
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
/* Created by: Mr. Coxall
 * Created on: Sep 2020
 * This program checks for a runtime error
 */

const prompt = require("prompt-sync")()

// input
const integerAsString = prompt("Enter an integer: ")

// process & output
const integerAsNumber = parseInt(integerAsString)

if (integerAsNumber != NaN) {
  console.log(`You entered: ${integerAsNumber}.`)
} else {
  console.log("Invalid input.")
}

console.log("\nDone.")
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#!/usr/bin/env python3
"""
Created by: Mr. Coxall
Created on: Sep 2020
This module checks for a runtime error
"""


def main() -> None:
    """The main() function checks for a runtime error, returns None."""

    # input
    integer_as_string = input("Enter an integer: ")

    # process & output
    try:
        integer_as_number = int(integer_as_string)
    except ValueError:
        print(f"The error was {ValueError}.")
    else:
        print(f"You entered: {integer_as_number}.")
    finally:
        print("Thanks for playing.")

    print("\nDone.")


if __name__ == "__main__":
    main()

Example Output

Code example output