What are Exceptions?
An exception is an error that occurs during program execution, disrupting the normal flow. Dart provides a robust exception‑handling mechanism to catch and respond to these errors gracefully, preventing crashes. Exceptions can be thrown by the Dart runtime (e.g., division by zero) or explicitly by your code using the throw keyword.
Types of Exceptions: Error vs Exception
Dart distinguishes two kinds of throwable objects:
Error– indicates a serious problem that should not be caught and handled; usually bugs in your code (e.g.,AssertionError,RangeError).
Exception– indicates a recoverable error that you can catch and handle (e.g.,IOException,FormatException).
In practice, you can throw any object, but it's best practice to throw Exception or a subclass of it for expected errors.
Throwing an Exception
Try / Catch / Finally
Use try to enclose code that might throw an exception, catch to handle it, and finally to run code regardless of whether an exception occurred (e.g., cleanup).
Catching Specific Exceptions
You can catch specific exception types using on before the catch clause. This allows you to handle different exceptions differently.
The catch clause can provide two arguments: the exception object and the stack trace. Use on without catch if you only need the type, or use on with catch to get the object.
Rethrowing Exceptions
Sometimes you want to handle an exception partially and then let it propagate further. Use rethrow to throw the same exception again.
Custom Exceptions
You can define your own exception classes by extending Exception. This makes error handling more expressive.
Asynchronous Error Handling
Errors in asynchronous code can be handled using try/catch inside an async function, or using .catchError on a Future. For streams, use the onError callback in listen() or the handleError transformer.
Best Practices
- Catch only exceptions you can handle. Let others propagate.
- Use specific exception types for better control.
- Always clean up resources in
finallyblocks.
- Always clean up resources in
- In asynchronous code, always handle errors either with
try/catchor.catchError.
- In asynchronous code, always handle errors either with
- For custom exceptions, extend
Exception(orErrorif truly unrecoverable).
- For custom exceptions, extend
- Use
rethrowto log or transform an exception before passing it up.
- Use
Complete Example
Key Takeaways
- Exceptions are used to handle errors gracefully.
- Use
try,catch,finallyto handle exceptions.
- Use
- Catch specific exceptions with
on.
- Catch specific exceptions with
- Define custom exceptions by extending
Exception.
- Define custom exceptions by extending
- Asynchronous errors are handled with
try/catchinasyncfunctions or.catchError.
- Asynchronous errors are handled with
- Always consider whether to let an exception propagate or handle it.