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 / countwhencountis0(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
EasyThe 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: potionOtherwise, print Slot , the number and is empty. For the input 7, the output is:
Slot 7 is emptyA 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
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String MethodsSearching in StringsReplace and TrimSplit and JoinRecap - Username Check4Dictionaries Part 2
Nested DictionariesArrays of DictionariesMerging DictionariesCopying DictionariesRecap - Frequency Counter2Advanced Decision Making
Match With VariablesMatch GuardsArray PatternsDictionary PatternsMembership ChecksRecap - Command Parser5Contact Book Application
Display MenuAdd Contact8Student Records Manager
Project OverviewAdd Student3Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysJagged ArraysCommon 2D Array PatternsRecap - Game Board6Sets with Dictionaries
What is a Set?Dictionary as a SetAdding and RemovingUnion and IntersectionSet DifferenceRecap - Remove Duplicates9Advanced Data Aggregation
Summing ValuesFinding Minimum and MaximumCustom SortingRecap - Dictionary Sorter12Basic Error Handling
What is Error Handling?Validating InputGuard ClausesReturning Error CodesRecap - Safe DivisionPractice on your own: Online GDScript compiler