Menu
CoddyTech

What is Error Handling?

Part of the Logic & Flow section of Coddy's GDScript journey. Lesson 66 of 78.

A program can stop in the middle because of an error. This code asks for slot 5 of an array that has only three elements:

var inventory := ["sword", "shield", "potion"]
var slot := 5
print(inventory[slot])
print("Done")

Godot reports Out of bounds get index '5' and the function stops at that line, so Done is never printed. This is a runtime error: the code is valid, but a value it gets while running makes one line impossible to run.

The runtime errors you meet most often are:

  • dividing a whole number by zero, as in 10 / count when count is 0 (the same for %)
  • reading a missing key with square brackets, as in player["mana"]
  • an index outside the array, as in inventory[5] above

Python and Java can catch an error after it happens, with try and except or catch. GDScript has no exceptions and no try. Error handling in GDScript means checking the values before the line that could fail, and deciding what to do instead:

if slot >= 0 and slot < inventory.size():
	print(inventory[slot])
else:
	print("Slot ", slot, " is empty")

The check needs both parts. A negative index such as -1 is not an error: it reads from the end of the array, which is not what a slot number means.

When the error happens inside a function you called, that function stops and returns an empty value, such as 0 or null, and the caller goes on with that wrong value. Some mistakes give a wrong value without any error: int("abc") is 0.

challenge icon

Challenge

Easy

The array inventory has four slots, numbered from 0. The program reads one line of input: a slot number (a whole number, possibly negative).

If the slot exists, print Slot , the number, : and the item. For the input 2, the output is:

Slot 2: potion

Otherwise, print Slot , the number and is empty. For the input 7, the output is:

Slot 7 is empty

A negative number is never a slot: for -1, print Slot -1 is empty. The program must never stop with an error.

Try it yourself

extends Node

func _ready():
	var inventory := ["sword", "shield", "potion", "bow"]
	var slot := int(OS.read_string_from_stdin())

	# Print the item in the slot, or that the slot is empty
	pass
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow

Practice on your own: Online GDScript compiler