Exception Handling in Dart: Handle Errors the Right Way

Learn exception handling in Dart with try-catch, on, finally, custom exceptions, and real Flutter-style examples. A beginner-friendly guide to writing safe and crash-free Dart code.

Introduction

No matter how well you write code, errors are unavoidable.
What matters is how your application handles those errors.

In Dart (and Flutter), exception handling helps you:

  • Prevent app crashes

  • Handle unexpected situations

  • Show meaningful error messages

  • Write stable and production-ready apps

In this article, we’ll understand what exceptions are, how Dart handles them, and best practices used in real Flutter applications.

What Is an Exception in Dart?

An exception is an error that occurs at runtime and disrupts the normal flow of a program.

Examples:

  • Dividing by zero

  • Accessing invalid list index

  • Network request failure

  • Null value access

If exceptions are not handled, your app will crash.

Difference Between Error and Exception

Error Exception
Serious problem Recoverable problem
Usually not handled Should be handled
Example: Out of memory Example: Invalid input

In Flutter apps, we mainly handle exceptions, not errors.

Using try and catch

The most common way to handle exceptions is using try-catch.

void main() { try { int result = 10 ~/ 0; print(result); } catch (e) { print("Exception occurred: $e"); } 

✔ Code inside try may throw an exception
catch executes if an error occurs

Catching Specific Exceptions with on

You can handle specific exceptions using the on keyword.

void main() { try { int result = 10 ~/ 0; } on IntegerDivisionByZeroException { print("Cannot divide by zero"); } catch (e) { print("Unknown error: $e"); } 

✔ More control
✔ Cleaner error handling

Using finally Block

The finally block always runs — whether an exception occurs or not.

void main() { try { print("Trying operation"); } catch (e) { print("Error occurred"); } finally { print("This always executes"); } 

Used commonly for:

  • Closing files

  • Cleaning resources

  • Stopping loaders in Flutter

Throwing an Exception Manually

You can throw exceptions using throw.

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

Usage:

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

✔ Useful for validation logic
✔ Common in business rules

Custom Exceptions in Dart

For better clarity, you can create your own exception classes.

class InvalidEmailException implements Exception { final String message; InvalidEmailException(this.message); @override String toString() => message; 

Usage:

void validateEmail(String email) { if (!email.contains("@")) { throw InvalidEmailException("Invalid email address"); } 

✔ Cleaner error handling
✔ Better debugging
✔ Professional code structure

Exception Handling in Flutter (Real Example)

In Flutter apps, exceptions commonly occur during API calls.

Future<void> fetchData() async { try { // API call throw Exception("Network error"); } catch (e) { print("Failed to fetch data: $e"); } 

In real apps:

  • Show snackbar or dialog

  • Log error

  • Retry operation

Using rethrow

Sometimes you want to handle an exception and pass it forward.

void processData() { try { fetchData(); } catch (e) { print("Logging error"); rethrow; } 

✔ Preserves original stack trace
✔ Useful in layered architecture

Common Mistakes

  • Catching exceptions but doing nothing

  • Overusing try-catch everywhere

  • Throwing generic exceptions only

  • Ignoring error messages

Best Practices

  • Catch only what you can handle

  • Use custom exceptions for clarity

  • Avoid empty catch blocks

  • Log errors properly

  • Show user-friendly messages in UI

Conclusion

Exception handling is a critical skill for Dart and Flutter developers.
It helps you write safe, stable, and maintainable applications.

A well-handled exception can turn a crash into a smooth user experience.

Share

What's Your Reaction?

Like Like 0
Dislike Dislike 0
Love Love 0
Funny Funny 0
Angry Angry 0
Sad Sad 0
Wow Wow 0