Dart Error Handling

Introduction of Error Handling:
Error handling is an indispensable aspect of programming, ensuring that applications can gracefully handle unexpected situations and provide meaningful feedback to users.
Dart, with its robust exception handling mechanisms, empowers developers to build resilient applications.
What is Exception?
Exception is an object that represents an abnormal condition or error that occurs during the execution of a program.
When an exceptional situation arises, such as a runtime error or an invalid operation, Dart throws an exception to indicate that something unexpected has happened.
In this blog, we'll explore the essentials of error handling with exceptions in Dart, covering throw statements, catch blocks, finally blocks, assert statements, Create custom exceptions, try...catch block and on..catch block.
1. Throw Statements:
In Dart, throw statements are used to raise exceptions when abnormal conditions occur during program execution. Here's how you can use throw statements to signal errors:
void validateAge(int age) {
if (age < 18) {
throw Exception('Age must be 18 or older');
}
}
2. Catch Blocks:
Catch blocks are used to handle exceptions thrown within a try block. Dart provides flexibility in catching specific types of exceptions or handling generic exceptions. Here's how you can catch and handle exceptions:
Using a try...catch block in dart.
void validateAge(int age) {
if (age < 18) {
throw Exception('Age must be 18 or older');
}
}
void main() {
try {
// Call a function that may throw an exception
validateAge(15);
} catch (e) {
// Handle the exception
print('Exception caught: $e');
}
}
Output:

Using an on…catch block in the dart.
void validateAge(int age) {
if (age < 18) {
throw Exception('Age must be 18 or older');
}
}
void main() {
try {
// Call a function that may throw an exception
validateAge(15);
} on Exception catch (e) {
// Handle the exception
print('Exception caught: $e');
}
}
3. Finally Blocks:
Finally blocks are executed regardless of whether an exception is thrown or caught.
They are commonly used to perform cleanup tasks, such as closing files or releasing resources. Here's an example of using finally blocks:
void validateAge(int age) {
if (age < 18) {
throw Exception('Age must be 18 or older');
}
}
void main() {
try {
// Call a function that may throw an exception
validateAge(15);
} catch (e) {
// Handle the exception
print('Exception caught: $e');
} finally {
// Cleanup code, executed regardless of whether an exception was thrown
print('Cleanup complete');
}
}
Output:

4. Writing Custom Exceptions:
Every exception class inherits from the Exception class. Dart enables creating custom exceptions by extending the existing ones.
Syntax: class Custom_exception_Name implements Exception { }
Creating custom exceptions in the dart.
// extending Class Age
// with Exception class
class Age implements Exception {
String error() => 'Jinali, your age is less than 18 ';
}
void main() {
int jinali_age1 = 20;
int jinali_age2 = 10;
try{
// Checking Age and
// calling if the
// exception occur
check(jinali_age1);
check(jinali_age2);
}
catch(e){
// Printing error
print(e.error());
}
}
// Checking Age
void check(int age){
if(age < 18){
throw new Age();
}
else
{
print("You are eligible to visit");
}
}
//Output:
You are eligible to visit
Geek, your age is less than 18
In the above example, we created a custom exception, Age. The code raised the exception if the entered amount is not within the excepted range, and we enclosed the function invocation in the try…catch block.
5. Assert Statements:
Assert statements are used to check for logical errors during development and testing. They help identify issues early in the development process. Here's how you can use assert statements:
void depositMoney(double amount) {
assert(amount > 0, 'Amount must be greater than zero');
// Deposit logic
}
void main() {
depositMoney(100); // Assertion passes
depositMoney(-50); // Assertion fails
}
Types of Exception
Built-in Exceptions in Dart:
The below table has a listing of principal dart exceptions.
| Sr. | Exceptions | Description |
| 1 | DefferedLoadException | It is thrown when a deferred library fails to load. |
| 2 | FormatException | It is the exception that is thrown when a string or some other data does not have an expected format |
| 3 | IntegerDivisionByZeroException | It is thrown when the number is divided by zero. |
| 4 | IOEException | It is the base class of input-output-related exceptions. |
| 5 | IsolateSpawnException | It is thrown when an isolated cannot be created. |
| 6 | Timeout | It is thrown when a scheduled timeout happens while waiting for an async result. |
Every built-in exception in Dart comes under a pre-defined class named Exception.



