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.
✔ 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.
✔ More control
✔ Cleaner error handling
Using finally Block
The finally block always runs — whether an exception occurs or not.
Used commonly for:
-
Closing files
-
Cleaning resources
-
Stopping loaders in Flutter
Throwing an Exception Manually
You can throw exceptions using throw.
Usage:
✔ Useful for validation logic
✔ Common in business rules
Custom Exceptions in Dart
For better clarity, you can create your own exception classes.
Usage:
✔ Cleaner error handling
✔ Better debugging
✔ Professional code structure
Exception Handling in Flutter (Real Example)
In Flutter apps, exceptions commonly occur during API calls.
In real apps:
-
Show snackbar or dialog
-
Log error
-
Retry operation
Using rethrow
Sometimes you want to handle an exception and pass it forward.
✔ Preserves original stack trace
✔ Useful in layered architecture
Common Mistakes
-
Catching exceptions but doing nothing
-
Overusing
try-catcheverywhere -
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
0
Dislike
0
Love
0
Funny
0
Angry
0
Sad
0
Wow
0