Dart Lesson 17 – Exceptions | Dataplexa

Exceptions in Dart

In this lesson, you will learn about exceptions in Dart. Exceptions are runtime errors that occur when a program encounters unexpected situations while executing.

Handling exceptions correctly helps prevent application crashes and ensures a smooth user experience.


What Is an Exception?

An exception is an error that happens during program execution. Unlike syntax errors, exceptions occur while the program is running.

Common real-world causes of exceptions include:

  • Invalid user input
  • Division by zero
  • File not found
  • Network or API failures

Real-World Example Without Exception Handling

Consider a billing system where a user enters a quantity.

int totalItems = int.parse("abc");
print(totalItems);

This code will crash because "abc" cannot be converted into an integer.


Using try and catch

The try block contains code that may throw an exception. The catch block handles the error gracefully.

try {
  int quantity = int.parse("abc");
  print(quantity);
} catch (e) {
  print("Invalid input detected");
}

Instead of crashing, the program now handles the error safely.


Accessing Error Details

The exception object contains useful error information.

try {
  double value = double.parse("xyz");
} catch (e) {
  print("Error: $e");
}

This is useful for debugging and logging errors.


Handling Specific Exceptions

You can catch specific exceptions instead of handling all errors generically.

try {
  int number = int.parse("abc");
} on FormatException {
  print("Please enter a valid number");
}

This approach is recommended when you know the expected error type.


Using finally Block

The finally block always executes, whether an exception occurs or not.

This is commonly used for cleanup operations such as closing files or connections.

try {
  int result = 10 ~/ 2;
  print(result);
} catch (e) {
  print("Error occurred");
} finally {
  print("Execution completed");
}

Division by Zero Example

Division by zero is a common runtime error.

try {
  int result = 10 ~/ 0;
  print(result);
} catch (e) {
  print("Cannot divide by zero");
}

Throwing Custom Exceptions

You can throw your own exceptions to enforce business rules.

void checkAge(int age) {
  if (age < 18) {
    throw Exception("Age must be 18 or above");
  }
  print("Access granted");
}

try {
  checkAge(16);
} catch (e) {
  print(e);
}

This is useful in validation logic.


Using tryParse Instead of Exceptions

Sometimes it is better to avoid exceptions entirely.

String input = "123";
int? value = int.tryParse(input);

if (value == null) {
  print("Invalid number");
} else {
  print("Valid number: $value");
}

This method improves performance and readability.


Best Practices for Exception Handling

  • Handle only expected exceptions
  • Avoid empty catch blocks
  • Use meaningful error messages
  • Prefer tryParse() when possible
  • Log errors in production systems

📝 Practice Exercises


Exercise 1

Handle a format exception when parsing a string to an integer.

Exercise 2

Use finally to print a message after execution.

Exercise 3

Create a function that throws an exception for invalid input.


✅ Practice Answers


Answer 1

try {
  int value = int.parse("abc");
} catch (e) {
  print("Invalid format");
}

Answer 2

try {
  print("Processing");
} finally {
  print("Done");
}

Answer 3

void validate(int value) {
  if (value < 0) {
    throw Exception("Negative value not allowed");
  }
}

try {
  validate(-5);
} catch (e) {
  print(e);
}

What’s Next?

In the next lesson, you will learn about File Handling in Dart, including reading from files, writing to files, and managing file paths.