SomonScriptDocsErrors and exceptions
Chapter 11 • Errors and exceptions

Error handling in SomonScript

With кӯшиш-гирифтан (try-catch) blocks and custom error classes, we can handle errors, show the user a clear message and keep the program from crashing.

1. A simple example: division by zero

In this example, we write a function that throws an exception when we try to divide by zero, and we handle this exception in a кӯшиш-гирифтан block.

Division with an error check

A function that checks for division by zero, and how to use a кӯшиш-гирифтан block.

example.som
// Division function with an error check
функсия тақсим_кардан(а: рақам, б: рақам): рақам {
  агар (б === 0) {
    партофтан нав Хато("Тақсим ба сифр иҷозат нест");
  }
  бозгашт а / б;
}

// Calling it with error handling
кӯшиш {
  тағ натиҷа: рақам = тақсим_кардан(10, 0);
  чоп.сабт("Натиҷа: " + натиҷа);
} гирифтан (хато) {
  чоп.хато("Хато: " + хато.message);
}
terminal
somon run errors-basic.som
Хато: Тақсим ба сифр иҷозат нест

2. A harder example: a custom error class

Now let's create a special error class for validating the data a user enters. This way we can tell different kinds of errors apart.

A custom error for validation

A custom error class and how it is used in validation functions.

example.som
// Custom error class for data validation
синф Хатои_тасдиқ мерос Хато {
  конструктор(паём: сатр) {
    супер(паём);
    ин.name = "Хатои_тасдиқ";
  }
}

функсия тасдиқи_синну_сол(синну_сол: рақам): беджавоб {
  агар (синну_сол < 0) {
    партофтан нав Хатои_тасдиқ("Синну сол набояд манфӣ бошад");
  }
  агар (синну_сол > 150) {
    партофтан нав Хатои_тасдиқ("Синну соли хеле калон");
  }
  чоп.сабт("Синну сол дуруст аст: " + синну_сол);
}

// Calling it with separate handling of our own error
кӯшиш {
  тасдиқи_синну_сол(-5);
} гирифтан (хато) {
  агар (хато instanceof Хатои_тасдиқ) {
    чоп.хато("Хатои тасдиқ: " + хато.message);
  } вагарна {
    чоп.хато("Хатои номаълум: " + хато);
  }
}
terminal
somon run errors-validate.som
Хатои тасдиқ: Синну сол набояд манфӣ бошад

3. Exercises

These exercises will help you get better at handling errors.

  1. Write a function that validates an age and throws an exception if it is invalid.
  2. Create a simple error log system that writes error messages to an array and prints them to the screen at the end.
  3. Create a custom error class "Database error" and use it in a function that connects to the database.