{"id":509,"date":"2026-11-13T07:49:44","date_gmt":"2026-11-13T07:49:44","guid":{"rendered":"https:\/\/moiks.com\/blog\/?p=509"},"modified":"2026-11-12T08:06:02","modified_gmt":"2026-11-12T08:06:02","slug":"dart-exception-handling-try-catch-custom-exceptions","status":"publish","type":"post","link":"https:\/\/moiks.com\/blog\/dart-exception-handling-try-catch-custom-exceptions\/","title":{"rendered":"Dart Exception Handling Explained: try, catch, on, finally, Custom Exceptions &#038; Practical Flutter Examples (2026 Guide)"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">Every production Flutter application must handle unexpected situations.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">An API request may fail because the device has no internet connection. A server may return an error. A JSON response may contain invalid data. A file may be missing, or an asynchronous operation may exceed its timeout.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Without proper error handling, these situations can cause confusing application behavior, unhandled exceptions, or crashes.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Dart provides a structured exception-handling system using <code>try<\/code>, <code>catch<\/code>, <code>on<\/code>, <code>finally<\/code>, <code>throw<\/code>, and <code>rethrow<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It also supports custom exception classes, stack traces, and asynchronous error propagation.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In this comprehensive <strong>Dart exception handling tutorial<\/strong>, we&#8217;ll explore these concepts from beginner to advanced and build a practical Flutter application that demonstrates error handling, recovery, and retry functionality.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This is <strong>Article 17<\/strong> in the Moiks Developer Blog Flutter Tutorials series.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">What You&#8217;ll Learn<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">By the end of this tutorial, you&#8217;ll understand:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>What exceptions and errors mean in Dart.<\/li>\n\n\n\n<li>How <code>try<\/code> and <code>catch<\/code> work.<\/li>\n\n\n\n<li>How to catch specific exception types using <code>on<\/code>.<\/li>\n\n\n\n<li>How to use <code>finally<\/code> for cleanup.<\/li>\n\n\n\n<li>How to throw and rethrow exceptions.<\/li>\n\n\n\n<li>How to create custom exception classes.<\/li>\n\n\n\n<li>How to inspect stack traces.<\/li>\n\n\n\n<li>How to handle asynchronous exceptions.<\/li>\n\n\n\n<li>How to handle timeout and simulated network failures.<\/li>\n\n\n\n<li>How to separate technical errors from user-friendly messages.<\/li>\n\n\n\n<li>How to implement retry functionality.<\/li>\n\n\n\n<li>How to test success, failure, and recovery scenarios.<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">1. What Is Exception Handling in Dart?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Exception handling is a mechanism for responding to failures during program execution.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Instead of allowing an exception to remain unhandled, an application can catch it and decide how to respond.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For example, consider a function that divides two numbers.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>double divide(double a, double b) {\n  if (b == 0) {\n    throw ArgumentError('Cannot divide by zero');\n  }\n\n  return a \/ b;\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">If the second argument is zero, the function throws an exception.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The caller can handle that failure:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>void main() {\n  try {\n    final result = divide(100, 0);\n    print(result);\n  } catch (error) {\n    print('Calculation failed: $error');\n  }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Instead of allowing the exception to escape, the program handles it.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Why Exception Handling Matters<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Proper error handling helps applications:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Display meaningful feedback.<\/li>\n\n\n\n<li>Recover from temporary failures.<\/li>\n\n\n\n<li>Avoid losing user-entered data.<\/li>\n\n\n\n<li>Release resources reliably.<\/li>\n\n\n\n<li>Record useful diagnostic information.<\/li>\n\n\n\n<li>Prevent expected failures from becoming unhandled exceptions.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">However, exception handling should not replace input validation or correct program logic.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">2. Understanding Exceptions vs Errors in Dart<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Dart distinguishes between exceptions and errors by convention and class hierarchy.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Exceptions<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Exceptions generally represent conditions that applications may reasonably anticipate or handle.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Examples include:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>FormatException<\/code><\/li>\n\n\n\n<li><code>TimeoutException<\/code><\/li>\n\n\n\n<li><code>IOException<\/code><\/li>\n\n\n\n<li><code>SocketException<\/code><\/li>\n\n\n\n<li>Custom application exceptions<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Errors<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Errors generally represent programming problems or situations that applications should not normally attempt to recover from.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Examples include:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>StateError<\/code><\/li>\n\n\n\n<li><code>RangeError<\/code><\/li>\n\n\n\n<li><code>TypeError<\/code><\/li>\n\n\n\n<li><code>AssertionError<\/code><\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Comparison<\/h3>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><tbody><tr><th>Exception<\/th><th>Error<\/th><\/tr><tr><td>Often represents an operational failure<\/td><td>Often represents a programming problem<\/td><\/tr><tr><td>May be recoverable<\/td><td>Usually requires fixing code<\/td><\/tr><tr><td>Common in networking and parsing<\/td><td>Common in invalid program state<\/td><\/tr><tr><td>Often handled at an application boundary<\/td><td>Usually logged and investigated<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Important:<\/strong> Dart allows any non-null object to be thrown. The distinction between <code>Exception<\/code> and <code>Error<\/code> is largely about intended usage.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For application-level failures, custom classes implementing <code>Exception<\/code> are generally preferable.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">3. Using try and catch in Dart<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>try<\/code> block contains code that may throw an exception.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>catch<\/code> block handles a thrown object.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Basic Syntax<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>try {\n  \/\/ Code that may fail\n} catch (error) {\n  \/\/ Handle the failure\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Example: Parsing a Number<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>void main() {\n  final input = 'abc';\n\n  try {\n    final number = int.parse(input);\n    print('Number: $number');\n  } catch (error) {\n    print('Invalid number: $error');\n  }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Since <code>'abc'<\/code> is not a valid integer, <code>int.parse()<\/code> throws a <code>FormatException<\/code>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Better Alternative for Expected Invalid Input<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Dart also provides <code>int.tryParse()<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>void main() {\n  final number = int.tryParse('abc');\n\n  if (number == null) {\n    print('Please enter a valid number');\n    return;\n  }\n\n  print(number);\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">For ordinary validation, a non-throwing API may be simpler than exception handling.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Best practice:<\/strong> Use exceptions for exceptional failures and validation APIs for expected user-input mistakes.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">4. Catching Specific Exceptions with on<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Catching every error with a generic <code>catch<\/code> block can make it difficult to distinguish different failure types.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Dart provides the <code>on<\/code> keyword for typed exception handling.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>void parseInput(String input) {\n  try {\n    final number = int.parse(input);\n    print(number);\n  } on FormatException {\n    print('The input is not a valid integer');\n  }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The handler executes when a <code>FormatException<\/code> is thrown.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Multiple Exception Types<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>void processValue(String input, int index) {\n  try {\n    final values = &#91;10, 20, 30];\n\n    final number = int.parse(input);\n    print(values&#91;index] + number);\n  } on FormatException {\n    print('Invalid number format');\n  } on RangeError {\n    print('Index is outside the valid range');\n  } catch (error) {\n    print('Unexpected failure: $error');\n  }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Why Catch Specific Types?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Different failures may require different recovery strategies.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For example:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Invalid input: Ask the user to correct the value.<\/li>\n\n\n\n<li>Network timeout: Offer a retry.<\/li>\n\n\n\n<li>Authentication failure: Ask the user to sign in.<\/li>\n\n\n\n<li>Server failure: Display a temporary service error.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Typed exception handling makes these decisions explicit.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">5. Understanding finally in Dart<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>finally<\/code> block executes when control leaves the associated <code>try<\/code> statement, whether the operation succeeds or throws.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It is useful for cleanup.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>void main() {\n  try {\n    print('Opening resource');\n\n    final result = 100 ~\/ 2;\n    print(result);\n  } catch (error) {\n    print('Failure: $error');\n  } finally {\n    print('Cleanup completed');\n  }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Opening resource\n50\nCleanup completed<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Resource Cleanup Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>import 'dart:io';\n\nFuture&lt;void&gt; writeLog(File file) async {\n  final sink = file.openWrite();\n\n  try {\n    sink.writeln('Application started');\n    await sink.flush();\n  } finally {\n    await sink.close();\n  }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>finally<\/code> block ensures that the code attempts to close the sink even when writing or flushing fails.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Important Consideration<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">If cleanup itself throws an exception, it can affect the error observed by the caller.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Production cleanup logic should account for this when preserving the original failure is important.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">6. Throwing Exceptions with throw<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>throw<\/code> keyword allows a function to signal a failure.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>void validateAge(int age) {\n  if (age &lt; 0) {\n    throw ArgumentError.value(\n      age,\n      'age',\n      'Age cannot be negative',\n    );\n  }\n\n  print('Valid age: $age');\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Usage:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>void main() {\n  try {\n    validateAge(-5);\n  } on ArgumentError catch (error) {\n    print(error.message);\n  }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">When Should You Throw?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Throw an exception when the operation cannot fulfill its contract.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Examples include:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Invalid method arguments.<\/li>\n\n\n\n<li>Missing required application data.<\/li>\n\n\n\n<li>Failed service operations.<\/li>\n\n\n\n<li>Invalid response formats.<\/li>\n\n\n\n<li>Unsupported operations.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Avoid throwing exceptions for normal UI decisions such as selecting a tab or dismissing a dialog.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">7. Understanding rethrow<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Sometimes a function needs to record or inspect an exception without fully handling it.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Dart provides <code>rethrow<\/code> to propagate the currently caught exception.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>Future&lt;void&gt; loadData() async {\n  try {\n    throw Exception('Server unavailable');\n  } catch (error, stackTrace) {\n    print('Logging error: $error');\n    print(stackTrace);\n\n    rethrow;\n  }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The caller can still handle the failure.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Future&lt;void&gt; main() async {\n  try {\n    await loadData();\n  } catch (error) {\n    print('Caller handled: $error');\n  }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">throw vs rethrow<\/h3>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><tbody><tr><th>Keyword<\/th><th>Behavior<\/th><\/tr><tr><td><code>throw<\/code><\/td><td>Throws an object as an exception<\/td><\/tr><tr><td><code>rethrow<\/code><\/td><td>Propagates the currently caught exception<\/td><\/tr><tr><td><code>throw error<\/code><\/td><td>Throws the caught object again, potentially changing stack-trace context<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">Use <code>rethrow<\/code> when you want to preserve the original exception propagation information.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">8. Understanding Stack Traces<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">A stack trace records information about the execution path associated with a failure.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It helps developers identify where an exception originated.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>void performCalculation() {\n  throw StateError('Calculation failed');\n}\n\nvoid main() {\n  try {\n    performCalculation();\n  } catch (error, stackTrace) {\n    print('Error: $error');\n    print('Stack trace: $stackTrace');\n  }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Why Stack Traces Matter<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Stack traces help with:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Identifying the failing function.<\/li>\n\n\n\n<li>Understanding nested calls.<\/li>\n\n\n\n<li>Debugging asynchronous failures.<\/li>\n\n\n\n<li>Investigating production incidents.<\/li>\n\n\n\n<li>Connecting errors to application versions.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Avoid displaying raw stack traces directly to end users.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">They are intended primarily for diagnostics.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">9. Creating Custom Exceptions in Dart<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Built-in exceptions are useful, but applications often need more meaningful domain-specific failures.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For example, a shopping application may need to distinguish between an unavailable product and a payment failure.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A Flutter application communicating with an API may need to distinguish network failures, server failures, and invalid responses.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Custom Exception Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>class ApiException implements Exception {\n  final String message;\n  final int? statusCode;\n\n  const ApiException(\n    this.message, {\n    this.statusCode,\n  });\n\n  @override\n  String toString() {\n    return 'ApiException: $message'\n        '${statusCode == null ? '' : ' ($statusCode)'}';\n  }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Usage:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>void checkResponse(int statusCode) {\n  if (statusCode &gt;= 500) {\n    throw ApiException(\n      'Server error',\n      statusCode: statusCode,\n    );\n  }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Benefits of Custom Exceptions<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Custom exceptions provide:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Meaningful failure categories.<\/li>\n\n\n\n<li>Consistent error handling.<\/li>\n\n\n\n<li>Better testability.<\/li>\n\n\n\n<li>Separation between service logic and UI.<\/li>\n\n\n\n<li>Easier recovery decisions.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">For larger applications, create a small, well-defined exception hierarchy rather than one generic exception for every failure.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">10. Creating a Typed Exception Hierarchy<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Consider an application that loads information from an API.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">We can define a base exception and specialized exceptions.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>abstract class AppException implements Exception {\n  final String message;\n\n  const AppException(this.message);\n\n  @override\n  String toString() =&gt; '$runtimeType: $message';\n}\n\nclass NetworkException extends AppException {\n  const NetworkException()\n      : super('No internet connection');\n}\n\nclass ServerException extends AppException {\n  const ServerException()\n      : super('Server temporarily unavailable');\n}\n\nclass DataException extends AppException {\n  const DataException()\n      : super('Invalid response data');\n}\n\nclass RequestTimeoutException extends AppException {\n  const RequestTimeoutException()\n      : super('Request timed out');\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Now callers can handle each category independently.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>try {\n  await fetchData();\n} on NetworkException {\n  print('Check your connection');\n} on ServerException {\n  print('Try again later');\n} on DataException {\n  print('Received invalid data');\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">This pattern scales better than comparing exception message strings.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">11. Exception Handling with async and await<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Asynchronous functions can complete with errors.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">When awaiting a future, Dart propagates a future error through the <code>await<\/code> expression.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>Future&lt;String&gt; fetchProfile() async {\n  await Future&lt;void&gt;.delayed(\n    const Duration(milliseconds: 500),\n  );\n\n  throw Exception('Unable to load profile');\n}\n\nFuture&lt;void&gt; main() async {\n  try {\n    final profile = await fetchProfile();\n    print(profile);\n  } catch (error) {\n    print('Profile error: $error');\n  }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>catch<\/code> block handles the error from the awaited future.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Common Mistake: Forgetting await<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>Future&lt;void&gt; loadProfile() async {\n  try {\n    fetchProfile();\n  } catch (error) {\n    print(error);\n  }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>try<\/code> block above does not reliably handle a future error because the future is neither awaited nor otherwise handled.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Correct Version<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>Future&lt;void&gt; loadProfile() async {\n  try {\n    await fetchProfile();\n  } catch (error) {\n    print('Handled: $error');\n  }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Best practice:<\/strong> Await asynchronous operations whose completion and errors matter to the current workflow.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">12. Handling TimeoutException<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Network operations may take too long.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Dart provides <code>Future.timeout()<\/code>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>import 'dart:async';\n\nFuture&lt;String&gt; slowRequest() async {\n  await Future&lt;void&gt;.delayed(\n    const Duration(seconds: 5),\n  );\n\n  return 'Success';\n}\n\nFuture&lt;void&gt; main() async {\n  try {\n    final result = await slowRequest().timeout(\n      const Duration(seconds: 2),\n    );\n\n    print(result);\n  } on TimeoutException {\n    print('The request took too long');\n  }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Important Timeout Behavior<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><code>Future.timeout()<\/code> does not automatically cancel the underlying operation.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The original future may continue running.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For real HTTP requests, use the timeout and cancellation mechanisms provided by the networking library where appropriate.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">13. Error Handling in Future.wait<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\"><code>Future.wait()<\/code> combines multiple asynchronous operations.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>Future&lt;String&gt; loadUser() async =&gt; 'Alex';\n\nFuture&lt;String&gt; loadSettings() async {\n  throw Exception('Settings unavailable');\n}\n\nFuture&lt;void&gt; main() async {\n  try {\n    final results = await Future.wait(&#91;\n      loadUser(),\n      loadSettings(),\n    ]);\n\n    print(results);\n  } catch (error) {\n    print('Combined operation failed: $error');\n  }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">If one operation fails, the combined future completes with an error according to <code>Future.wait()<\/code> semantics.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Important Detail<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Other started futures are not automatically canceled when one fails.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If partial success is acceptable, consider handling failures separately for each operation or using a result type that represents success and failure explicitly.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">14. Handling Errors in Streams<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Streams can emit both data events and error events.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>Stream&lt;int&gt; numberStream() async* {\n  yield 1;\n  yield 2;\n\n  throw Exception('Stream failed');\n}\n\nFuture&lt;void&gt; main() async {\n  try {\n    await for (final number in numberStream()) {\n      print(number);\n    }\n  } catch (error) {\n    print('Stream error: $error');\n  }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Expected output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>1\n2\nStream error: Exception: Stream failed<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">You can also handle errors through <code>listen()<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>final subscription = numberStream().listen(\n  (value) {\n    print(value);\n  },\n  onError: (Object error, StackTrace stackTrace) {\n    print('Stream failed: $error');\n  },\n);<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Manage subscriptions appropriately when their owning component is disposed.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">15. Practical Flutter Project: API Error Handling Lab<\/h1>\n\n\n\n<p class=\"wp-block-paragraph\">Let&#8217;s build a complete Flutter application demonstrating exception handling in a realistic UI.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The application will simulate an API that can succeed or fail in different ways.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Users can select a scenario, load data, inspect the result, and retry failed requests.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Features<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Material 3 interface.<\/li>\n\n\n\n<li>Simulated API requests.<\/li>\n\n\n\n<li>Successful response handling.<\/li>\n\n\n\n<li>Network failure simulation.<\/li>\n\n\n\n<li>Server failure simulation.<\/li>\n\n\n\n<li>Invalid response handling.<\/li>\n\n\n\n<li>Timeout simulation.<\/li>\n\n\n\n<li>Custom exception hierarchy.<\/li>\n\n\n\n<li>User-friendly error messages.<\/li>\n\n\n\n<li>Retry functionality.<\/li>\n\n\n\n<li>Loading and empty states.<\/li>\n\n\n\n<li>Unit and widget tests.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">The project works offline and requires no third-party packages.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Step 1: Create the Project<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>flutter create dart_exception_demo\ncd dart_exception_demo<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Project Structure<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>lib\/\n\u251c\u2500\u2500 main.dart\n\u251c\u2500\u2500 exceptions\/\n\u2502   \u2514\u2500\u2500 app_exception.dart\n\u251c\u2500\u2500 models\/\n\u2502   \u2514\u2500\u2500 user_profile.dart\n\u251c\u2500\u2500 services\/\n\u2502   \u2514\u2500\u2500 profile_service.dart\n\u2514\u2500\u2500 widgets\/\n    \u2514\u2500\u2500 error_panel.dart\n\ntest\/\n\u251c\u2500\u2500 profile_service_test.dart\n\u2514\u2500\u2500 widget_test.dart<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Step 2: Create Custom Exceptions<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Create <code>lib\/exceptions\/app_exception.dart<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>abstract class AppException implements Exception {\n  final String message;\n\n  const AppException(this.message);\n\n  @override\n  String toString() =&gt; '$runtimeType: $message';\n}\n\nclass NetworkException extends AppException {\n  const NetworkException()\n      : super('No internet connection');\n}\n\nclass ServerException extends AppException {\n  const ServerException()\n      : super('Server temporarily unavailable');\n}\n\nclass InvalidDataException extends AppException {\n  const InvalidDataException()\n      : super('Invalid response data');\n}\n\nclass RequestTimeoutException extends AppException {\n  const RequestTimeoutException()\n      : super('Request timed out');\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Each exception represents a specific failure category.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The UI will use these categories to display appropriate messages.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Step 3: Create the User Profile Model<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Create <code>lib\/models\/user_profile.dart<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import '..\/exceptions\/app_exception.dart';\n\nclass UserProfile {\n  final int id;\n  final String name;\n  final String email;\n\n  const UserProfile({\n    required this.id,\n    required this.name,\n    required this.email,\n  });\n\n  factory UserProfile.fromJson(\n    Map&lt;String, dynamic&gt; json,\n  ) {\n    final id = json&#91;'id'];\n    final name = json&#91;'name'];\n    final email = json&#91;'email'];\n\n    if (id is! int ||\n        name is! String ||\n        email is! String ||\n        name.trim().isEmpty ||\n        email.trim().isEmpty) {\n      throw const InvalidDataException();\n    }\n\n    return UserProfile(\n      id: id,\n      name: name,\n      email: email,\n    );\n  }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The factory validates the required fields before creating a profile.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If the response is malformed, it throws <code>InvalidDataException<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In a production application, more comprehensive validation may be appropriate.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Step 4: Create the API Simulation Service<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Create <code>lib\/services\/profile_service.dart<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import 'dart:async';\n\nimport '..\/exceptions\/app_exception.dart';\nimport '..\/models\/user_profile.dart';\n\nenum ApiScenario {\n  success,\n  networkError,\n  serverError,\n  invalidData,\n  timeout,\n}\n\nextension ApiScenarioLabel on ApiScenario {\n  String get label {\n    switch (this) {\n      case ApiScenario.success:\n        return 'Success';\n      case ApiScenario.networkError:\n        return 'Network Error';\n      case ApiScenario.serverError:\n        return 'Server Error';\n      case ApiScenario.invalidData:\n        return 'Invalid Data';\n      case ApiScenario.timeout:\n        return 'Timeout';\n    }\n  }\n}\n\nclass ProfileService {\n  final Duration responseDelay;\n  final Duration requestTimeout;\n\n  const ProfileService({\n    this.responseDelay =\n        const Duration(milliseconds: 600),\n    this.requestTimeout =\n        const Duration(seconds: 2),\n  });\n\n  Future&lt;UserProfile&gt; fetchProfile(\n    ApiScenario scenario,\n  ) async {\n    try {\n      return await _simulateRequest(scenario).timeout(\n        requestTimeout,\n      );\n    } on TimeoutException {\n      throw const RequestTimeoutException();\n    }\n  }\n\n  Future&lt;UserProfile&gt; _simulateRequest(\n    ApiScenario scenario,\n  ) async {\n    if (scenario == ApiScenario.timeout) {\n      await Future&lt;void&gt;.delayed(\n        requestTimeout +\n            const Duration(milliseconds: 100),\n      );\n    } else {\n      await Future&lt;void&gt;.delayed(responseDelay);\n    }\n\n    switch (scenario) {\n      case ApiScenario.success:\n        return UserProfile.fromJson({\n          'id': 101,\n          'name': 'Flutter Developer',\n          'email': 'developer@example.com',\n        });\n\n      case ApiScenario.networkError:\n        throw const NetworkException();\n\n      case ApiScenario.serverError:\n        throw const ServerException();\n\n      case ApiScenario.invalidData:\n        return UserProfile.fromJson({\n          'id': 'invalid-id',\n          'name': null,\n          'email': 123,\n        });\n\n      case ApiScenario.timeout:\n        return UserProfile.fromJson({\n          'id': 101,\n          'name': 'Delayed User',\n          'email': 'delayed@example.com',\n        });\n    }\n  }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">How the Service Works<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The service uses an enum to simulate five API scenarios.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Success:<\/strong> Returns a valid user profile.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Network Error:<\/strong> Throws <code>NetworkException<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Server Error:<\/strong> Throws <code>ServerException<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Invalid Data:<\/strong> Attempts to parse an invalid response, resulting in <code>InvalidDataException<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Timeout:<\/strong> Delays longer than the configured timeout, resulting in <code>RequestTimeoutException<\/code>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Why Use a Service Layer?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The service is responsible for data loading and technical error classification.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The widget is responsible for displaying loading, success, and error states.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This separation makes the code easier to test and maintain.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Step 5: Create a Reusable Error Widget<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Create <code>lib\/widgets\/error_panel.dart<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import 'package:flutter\/material.dart';\n\nclass ErrorPanel extends StatelessWidget {\n  final String title;\n  final String message;\n  final VoidCallback onRetry;\n\n  const ErrorPanel({\n    super.key,\n    required this.title,\n    required this.message,\n    required this.onRetry,\n  });\n\n  @override\n  Widget build(BuildContext context) {\n    final colors = Theme.of(context).colorScheme;\n\n    return Card(\n      child: Padding(\n        padding: const EdgeInsets.all(20),\n        child: Column(\n          mainAxisSize: MainAxisSize.min,\n          children: &#91;\n            Icon(\n              Icons.error_outline,\n              size: 48,\n              color: colors.error,\n            ),\n            const SizedBox(height: 12),\n            Text(\n              title,\n              style: Theme.of(context)\n                  .textTheme\n                  .titleLarge,\n              textAlign: TextAlign.center,\n            ),\n            const SizedBox(height: 8),\n            Text(\n              message,\n              textAlign: TextAlign.center,\n            ),\n            const SizedBox(height: 16),\n            FilledButton.icon(\n              onPressed: onRetry,\n              icon: const Icon(Icons.refresh),\n              label: const Text('Retry'),\n            ),\n          ],\n        ),\n      ),\n    );\n  }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">This reusable component provides a consistent error experience.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The same pattern can be used for API errors, database failures, or other recoverable operations.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Step 6: Build the Flutter Application<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Replace <code>lib\/main.dart<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import 'package:flutter\/material.dart';\n\nimport 'exceptions\/app_exception.dart';\nimport 'models\/user_profile.dart';\nimport 'services\/profile_service.dart';\nimport 'widgets\/error_panel.dart';\n\nvoid main() {\n  runApp(const ExceptionDemoApp());\n}\n\nclass ExceptionDemoApp extends StatelessWidget {\n  const ExceptionDemoApp({super.key});\n\n  @override\n  Widget build(BuildContext context) {\n    return MaterialApp(\n      title: 'Flutter Error Handling Lab',\n      debugShowCheckedModeBanner: false,\n      theme: ThemeData(\n        colorScheme: ColorScheme.fromSeed(\n          seedColor: const Color(0xFF004B64),\n        ),\n        useMaterial3: true,\n      ),\n      home: const ErrorHandlingScreen(),\n    );\n  }\n}\n\nclass ErrorHandlingScreen extends StatefulWidget {\n  final ProfileService service;\n\n  const ErrorHandlingScreen({\n    super.key,\n    this.service = const ProfileService(),\n  });\n\n  @override\n  State&lt;ErrorHandlingScreen&gt; createState() =&gt;\n      _ErrorHandlingScreenState();\n}\n\nclass _ErrorHandlingScreenState\n    extends State&lt;ErrorHandlingScreen&gt; {\n  ApiScenario selectedScenario = ApiScenario.success;\n\n  UserProfile? profile;\n  AppException? appError;\n\n  bool isLoading = false;\n  int requestVersion = 0;\n\n  Future&lt;void&gt; loadProfile() async {\n    if (isLoading) return;\n\n    final version = ++requestVersion;\n\n    setState(() {\n      isLoading = true;\n      profile = null;\n      appError = null;\n    });\n\n    try {\n      final result = await widget.service.fetchProfile(\n        selectedScenario,\n      );\n\n      if (!mounted || version != requestVersion) {\n        return;\n      }\n\n      setState(() {\n        profile = result;\n      });\n    } on AppException catch (error, stackTrace) {\n      debugPrint('Profile request failed: $error');\n      debugPrintStack(stackTrace: stackTrace);\n\n      if (!mounted || version != requestVersion) {\n        return;\n      }\n\n      setState(() {\n        appError = error;\n      });\n    } catch (error, stackTrace) {\n      debugPrint('Unexpected error: $error');\n      debugPrintStack(stackTrace: stackTrace);\n\n      if (!mounted || version != requestVersion) {\n        return;\n      }\n\n      setState(() {\n        appError = const ServerException();\n      });\n    } finally {\n      if (mounted &amp;&amp; version == requestVersion) {\n        setState(() {\n          isLoading = false;\n        });\n      }\n    }\n  }\n\n  String errorTitle(AppException error) {\n    if (error is NetworkException) {\n      return 'Connection Problem';\n    }\n\n    if (error is ServerException) {\n      return 'Service Unavailable';\n    }\n\n    if (error is InvalidDataException) {\n      return 'Invalid Response';\n    }\n\n    if (error is RequestTimeoutException) {\n      return 'Request Timed Out';\n    }\n\n    return 'Something Went Wrong';\n  }\n\n  String errorMessage(AppException error) {\n    if (error is NetworkException) {\n      return 'Check your internet connection '\n          'and try again.';\n    }\n\n    if (error is ServerException) {\n      return 'The service is temporarily '\n          'unavailable. Please try later.';\n    }\n\n    if (error is InvalidDataException) {\n      return 'We received unexpected data. '\n          'Please try again.';\n    }\n\n    if (error is RequestTimeoutException) {\n      return 'The request took too long. '\n          'Please retry.';\n    }\n\n    return 'An unexpected problem occurred.';\n  }\n\n  Widget buildProfile(UserProfile user) {\n    return Card(\n      child: Padding(\n        padding: const EdgeInsets.all(20),\n        child: Column(\n          children: &#91;\n            const CircleAvatar(\n              radius: 32,\n              child: Icon(\n                Icons.person,\n                size: 32,\n              ),\n            ),\n            const SizedBox(height: 12),\n            Text(\n              user.name,\n              style: Theme.of(context)\n                  .textTheme\n                  .titleLarge,\n            ),\n            const SizedBox(height: 8),\n            Text(user.email),\n            const SizedBox(height: 8),\n            Text('User ID: ${user.id}'),\n            const SizedBox(height: 12),\n            const Chip(\n              label: Text('Request Successful'),\n              avatar: Icon(\n                Icons.check_circle_outline,\n              ),\n            ),\n          ],\n        ),\n      ),\n    );\n  }\n\n  Widget buildResult() {\n    if (isLoading) {\n      return const Center(\n        child: Column(\n          children: &#91;\n            CircularProgressIndicator(),\n            SizedBox(height: 12),\n            Text('Loading profile...'),\n          ],\n        ),\n      );\n    }\n\n    if (appError != null) {\n      return ErrorPanel(\n        title: errorTitle(appError!),\n        message: errorMessage(appError!),\n        onRetry: loadProfile,\n      );\n    }\n\n    if (profile != null) {\n      return buildProfile(profile!);\n    }\n\n    return const Center(\n      child: Text(\n        'Select a scenario and load the profile.',\n        textAlign: TextAlign.center,\n      ),\n    );\n  }\n\n  @override\n  void dispose() {\n    requestVersion++;\n    super.dispose();\n  }\n\n  @override\n  Widget build(BuildContext context) {\n    return Scaffold(\n      appBar: AppBar(\n        title: const Text(\n          'Flutter Error Handling Lab',\n        ),\n        centerTitle: true,\n      ),\n      body: SafeArea(\n        child: Center(\n          child: ConstrainedBox(\n            constraints: const BoxConstraints(\n              maxWidth: 700,\n            ),\n            child: ListView(\n              padding: const EdgeInsets.all(16),\n              children: &#91;\n                Card(\n                  child: Padding(\n                    padding: const EdgeInsets.all(20),\n                    child: Column(\n                      children: &#91;\n                        const Icon(\n                          Icons.shield_outlined,\n                          size: 52,\n                          color: Color(0xFF004B64),\n                        ),\n                        const SizedBox(height: 12),\n                        Text(\n                          'Dart Exception Handling',\n                          style: Theme.of(context)\n                              .textTheme\n                              .headlineSmall,\n                          textAlign: TextAlign.center,\n                        ),\n                        const SizedBox(height: 8),\n                        const Text(\n                          'Explore API failures, custom '\n                          'exceptions, timeout handling '\n                          'and retry functionality.',\n                          textAlign: TextAlign.center,\n                        ),\n                      ],\n                    ),\n                  ),\n                ),\n\n                const SizedBox(height: 20),\n\n                DropdownButtonFormField&lt;ApiScenario&gt;(\n                  initialValue: selectedScenario,\n                  decoration: const InputDecoration(\n                    labelText: 'API Scenario',\n                    border: OutlineInputBorder(),\n                  ),\n                  items: &#91;\n                    for (final scenario\n                        in ApiScenario.values)\n                      DropdownMenuItem(\n                        value: scenario,\n                        child: Text(scenario.label),\n                      ),\n                  ],\n                  onChanged: isLoading\n                      ? null\n                      : (scenario) {\n                          if (scenario == null) return;\n\n                          setState(() {\n                            selectedScenario = scenario;\n                            profile = null;\n                            appError = null;\n                          });\n                        },\n                ),\n\n                const SizedBox(height: 16),\n\n                FilledButton.icon(\n                  onPressed: isLoading\n                      ? null\n                      : loadProfile,\n                  icon: const Icon(Icons.cloud_download),\n                  label: const Text('Load Profile'),\n                ),\n\n                const SizedBox(height: 24),\n\n                buildResult(),\n              ],\n            ),\n          ),\n        ),\n      ),\n    );\n  }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Understanding the UI<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The application follows a simple request lifecycle.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Idle:<\/strong> The user selects a scenario.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Loading:<\/strong> A progress indicator appears.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Success:<\/strong> The profile information is displayed.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Failure:<\/strong> A reusable error panel displays a user-friendly message.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Retry:<\/strong> The user can repeat the request.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The widget also checks <code>mounted<\/code> and uses a request version to avoid applying results after disposal or from outdated requests.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Production Logging Note<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The example uses <code>debugPrint()<\/code> and <code>debugPrintStack()<\/code> to demonstrate diagnostics.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For production applications, use an appropriate logging and crash-reporting strategy. Avoid logging sensitive information, access tokens, passwords, or unnecessary personal data.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Step 7: Run the Application<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>flutter run<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Test the Different Scenarios<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Success<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Select <code>Success<\/code> and tap <strong>Load Profile<\/strong>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The application displays:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Flutter Developer\ndeveloper@example.com\nUser ID: 101\nRequest Successful<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Network Error<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Select <code>Network Error<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The application displays a connection-related message and a Retry button.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Server Error<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Select <code>Server Error<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The application displays a temporary service failure message.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Invalid Data<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Select <code>Invalid Data<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The model rejects the malformed response.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Timeout<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Select <code>Timeout<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The request exceeds the configured timeout and displays a timeout error.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The application remains usable after each simulated failure.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">16. Unit Testing Dart Exceptions<\/h1>\n\n\n\n<p class=\"wp-block-paragraph\">Create <code>test\/profile_service_test.dart<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import 'package:flutter_test\/flutter_test.dart';\n\nimport 'package:dart_exception_demo\/exceptions\/app_exception.dart';\nimport 'package:dart_exception_demo\/models\/user_profile.dart';\nimport 'package:dart_exception_demo\/services\/profile_service.dart';\n\nvoid main() {\n  late ProfileService service;\n\n  setUp(() {\n    service = const ProfileService(\n      responseDelay: Duration.zero,\n      requestTimeout:\n          Duration(milliseconds: 20),\n    );\n  });\n\n  test('Loads a valid user profile', () async {\n    final profile = await service.fetchProfile(\n      ApiScenario.success,\n    );\n\n    expect(profile.id, 101);\n    expect(profile.name, 'Flutter Developer');\n  });\n\n  test('Throws NetworkException', () async {\n    await expectLater(\n      service.fetchProfile(\n        ApiScenario.networkError,\n      ),\n      throwsA(isA&lt;NetworkException&gt;()),\n    );\n  });\n\n  test('Throws ServerException', () async {\n    await expectLater(\n      service.fetchProfile(\n        ApiScenario.serverError,\n      ),\n      throwsA(isA&lt;ServerException&gt;()),\n    );\n  });\n\n  test('Throws InvalidDataException', () async {\n    await expectLater(\n      service.fetchProfile(\n        ApiScenario.invalidData,\n      ),\n      throwsA(isA&lt;InvalidDataException&gt;()),\n    );\n  });\n\n  test('Throws RequestTimeoutException', () async {\n    await expectLater(\n      service.fetchProfile(\n        ApiScenario.timeout,\n      ),\n      throwsA(isA&lt;RequestTimeoutException&gt;()),\n    );\n  });\n\n  test('Rejects malformed profile data', () {\n    expect(\n      () =&gt; UserProfile.fromJson({\n        'id': 'invalid',\n        'name': null,\n        'email': 123,\n      }),\n      throwsA(isA&lt;InvalidDataException&gt;()),\n    );\n  });\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">What These Tests Verify<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The tests cover:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Successful API responses.<\/li>\n\n\n\n<li>Network failures.<\/li>\n\n\n\n<li>Server failures.<\/li>\n\n\n\n<li>Invalid response data.<\/li>\n\n\n\n<li>Timeout conversion.<\/li>\n\n\n\n<li>Model validation.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Run:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>flutter test test\/profile_service_test.dart<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">17. Flutter Widget Testing<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Create <code>test\/widget_test.dart<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import 'package:flutter\/material.dart';\nimport 'package:flutter_test\/flutter_test.dart';\n\nimport 'package:dart_exception_demo\/main.dart';\nimport 'package:dart_exception_demo\/services\/profile_service.dart';\n\nvoid main() {\n  testWidgets(\n    'Displays the application title',\n    (tester) async {\n      await tester.pumpWidget(\n        const ExceptionDemoApp(),\n      );\n\n      expect(\n        find.text('Flutter Error Handling Lab'),\n        findsOneWidget,\n      );\n    },\n  );\n\n  testWidgets(\n    'Displays the scenario selector',\n    (tester) async {\n      await tester.pumpWidget(\n        const ExceptionDemoApp(),\n      );\n\n      expect(\n        find.byType(\n          DropdownButtonFormField&lt;ApiScenario&gt;,\n        ),\n        findsOneWidget,\n      );\n\n      expect(\n        find.text('Load Profile'),\n        findsOneWidget,\n      );\n    },\n  );\n\n  testWidgets(\n    'Displays a successful profile',\n    (tester) async {\n      await tester.pumpWidget(\n        const MaterialApp(\n          home: ErrorHandlingScreen(\n            service: ProfileService(\n              responseDelay: Duration.zero,\n            ),\n          ),\n        ),\n      );\n\n      await tester.tap(\n        find.text('Load Profile'),\n      );\n\n      await tester.pump();\n      await tester.pump(\n        const Duration(milliseconds: 10),\n      );\n\n      expect(\n        find.text('Flutter Developer'),\n        findsOneWidget,\n      );\n\n      expect(\n        find.text('Request Successful'),\n        findsOneWidget,\n      );\n    },\n  );\n\n  testWidgets(\n    'Displays loading state',\n    (tester) async {\n      await tester.pumpWidget(\n        const ExceptionDemoApp(),\n      );\n\n      await tester.tap(\n        find.text('Load Profile'),\n      );\n\n      await tester.pump();\n\n      expect(\n        find.byType(CircularProgressIndicator),\n        findsOneWidget,\n      );\n    },\n  );\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Running Tests<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>flutter test<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Run static analysis:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>flutter analyze<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Recommended Additional Tests<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">For production projects, also test:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Changing error scenarios.<\/li>\n\n\n\n<li>Retry after a failed request.<\/li>\n\n\n\n<li>Disposing the screen during a request.<\/li>\n\n\n\n<li>Multiple rapid user interactions.<\/li>\n\n\n\n<li>Error message accessibility.<\/li>\n\n\n\n<li>Different screen sizes.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">For widget tests involving timeouts, prefer deterministic fake services or controlled fake time rather than real network requests.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">18. FlutterError.onError vs PlatformDispatcher.onError<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Dart exception handling inside services is only one part of application reliability.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Flutter also provides mechanisms for reporting errors that escape normal application code.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">FlutterError.onError<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Flutter uses <code>FlutterError.onError<\/code> to report many errors caught by the Flutter framework.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>void main() {\n  FlutterError.onError = (details) {\n    FlutterError.presentError(details);\n  };\n\n  runApp(const ExceptionDemoApp());\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">PlatformDispatcher.onError<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><code>PlatformDispatcher.onError<\/code> can handle certain unhandled errors on the root isolate that are not caught by the Flutter framework.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import 'dart:ui';\n\nvoid main() {\n  PlatformDispatcher.instance.onError = (\n    error,\n    stackTrace,\n  ) {\n    \/\/ Send error details to an approved\n    \/\/ application logging system.\n    return true;\n  };\n\n  runApp(const ExceptionDemoApp());\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Returning <code>true<\/code> indicates that the handler has handled the error.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Important Limitations<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">These handlers are not substitutes for local exception handling.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">They do not guarantee recovery from every crash or native failure.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Errors in separately spawned isolates may require their own error-reporting mechanisms.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For production applications, configure framework and platform error reporting carefully and preserve useful diagnostic information.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">19. Error Handling in Flutter Architecture<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">As applications grow, error handling should be organized into layers.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A common structure is:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Flutter UI\n    |\n    v\nState \/ ViewModel\n    |\n    v\nRepository\n    |\n    v\nAPI \/ Database \/ Local Storage<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Data Layer<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Handles low-level failures such as network errors, invalid responses, and storage exceptions.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Repository Layer<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Converts implementation-specific failures into meaningful application-level exceptions or result types.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">State Layer<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Decides whether to retry, preserve existing data, or expose an error state.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">UI Layer<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Displays user-friendly messages and recovery actions.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This separation prevents widgets from becoming tightly coupled to HTTP status codes or low-level exception messages.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">20. Exceptions vs Result Types<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Not every failure needs to be represented by a thrown exception.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Some applications use a result type for expected outcomes.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>sealed class Result&lt;T&gt; {\n  const Result();\n}\n\nclass Success&lt;T&gt; extends Result&lt;T&gt; {\n  final T data;\n\n  const Success(this.data);\n}\n\nclass Failure&lt;T&gt; extends Result&lt;T&gt; {\n  final String message;\n\n  const Failure(this.message);\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Usage:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Future&lt;Result&lt;String&gt;&gt; loadUsername() async {\n  try {\n    return const Success('Flutter Developer');\n  } catch (error) {\n    return const Failure(\n      'Unable to load username',\n    );\n  }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">When to Use Result Types<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Result types can be useful when failures are expected parts of a workflow and callers must explicitly handle both success and failure.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Examples include:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Login validation.<\/li>\n\n\n\n<li>Form submission.<\/li>\n\n\n\n<li>Payment outcomes.<\/li>\n\n\n\n<li>Permission decisions.<\/li>\n\n\n\n<li>Repository operations.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">When to Use Exceptions<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Exceptions remain useful for unexpected failures and APIs that naturally communicate errors by throwing.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Both approaches can coexist.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Choose a consistent strategy that fits your application&#8217;s architecture.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">21. Common Exception Handling Mistakes<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 1: Catching Everything and Ignoring It<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Avoid:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>try {\n  await loadData();\n} catch (_) {}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Silently swallowing failures makes debugging difficult.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 2: Showing Raw Exceptions to Users<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Avoid displaying:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>SocketException: Failed host lookup<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Instead, display a meaningful message such as:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Unable to connect. Check your internet connection.<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 3: Using Exceptions for Ordinary Validation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Prefer <code>tryParse()<\/code> or explicit validation when invalid input is expected.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 4: Forgetting await<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">An unawaited future may fail outside the intended <code>try\/catch<\/code> block.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 5: Losing Stack Traces<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use <code>rethrow<\/code> when propagating a caught exception without changing its meaning.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 6: Retrying Every Failure<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Retrying invalid data or authorization failures repeatedly may not help.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Retry policies should depend on the failure category.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 7: Retrying Without Limits<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Unbounded retries can overload services and drain device resources.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 8: Ignoring Widget Lifecycle<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">An asynchronous request may finish after its screen is disposed.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Check <code>mounted<\/code> and cancel supported operations where appropriate.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 9: Treating Every Error as Recoverable<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Programming errors should usually be investigated and fixed rather than hidden behind generic recovery logic.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 10: Logging Sensitive Information<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Avoid recording passwords, authentication tokens, private user data, or unnecessary request payloads.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">22. Best Practices for Production Flutter Apps<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Use the following guidelines:<\/p>\n\n\n\n<ol start=\"1\" class=\"wp-block-list\">\n<li>Catch specific exception types whenever practical.<\/li>\n\n\n\n<li>Use custom exceptions for meaningful domain failures.<\/li>\n\n\n\n<li>Keep technical diagnostics separate from user-facing messages.<\/li>\n\n\n\n<li>Preserve stack traces when propagating failures.<\/li>\n\n\n\n<li>Use <code>finally<\/code> for appropriate resource cleanup.<\/li>\n\n\n\n<li>Handle asynchronous future and stream errors explicitly.<\/li>\n\n\n\n<li>Implement bounded retries only for suitable transient failures.<\/li>\n\n\n\n<li>Prevent stale requests from updating disposed or outdated screens.<\/li>\n\n\n\n<li>Avoid leaking sensitive data into logs.<\/li>\n\n\n\n<li>Test success, failure, timeout, and recovery scenarios.<\/li>\n\n\n\n<li>Use centralized reporting for unexpected application errors.<\/li>\n\n\n\n<li>Keep error-handling logic consistent across repositories and features.<\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">A reliable application does not simply avoid errors.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It responds to expected failures predictably and makes unexpected failures easier to investigate.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h1 class=\"wp-block-heading\">23. Frequently Asked Questions<\/h1>\n\n\n\n<h3 class=\"wp-block-heading\">What is exception handling in Dart?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Exception handling is the process of detecting and responding to thrown failures using constructs such as <code>try<\/code>, <code>catch<\/code>, <code>on<\/code>, and <code>finally<\/code>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What is the difference between Exception and Error in Dart?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Exceptions generally represent anticipated operational failures, while errors commonly indicate programming problems or invalid program states.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What does try do in Dart?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">A <code>try<\/code> block contains code whose thrown failures can be handled by associated catch clauses.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What does catch do in Dart?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">A <code>catch<\/code> clause receives a thrown object and allows the application to handle it.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What is the on keyword in Dart?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>on<\/code> keyword restricts an exception handler to a particular type.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What does finally do in Dart?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">A <code>finally<\/code> block executes when control leaves the associated try statement, making it useful for cleanup.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What is throw in Dart?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><code>throw<\/code> signals a failure by throwing an object.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What is rethrow in Dart?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><code>rethrow<\/code> propagates the currently caught exception while preserving its original exception context.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Can I create custom exceptions in Dart?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Yes. You can define classes that implement <code>Exception<\/code> or extend your own exception hierarchy.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">How do I handle Future errors?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Await the future inside a <code>try\/catch<\/code> block or use the future&#8217;s error-handling APIs appropriately.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">How do I handle Stream errors?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use <code>try\/catch<\/code> with <code>await for<\/code>, or provide an <code>onError<\/code> handler when subscribing to a stream.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What is TimeoutException?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><code>TimeoutException<\/code> represents a timeout condition in Dart&#8217;s asynchronous APIs.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Does Future.timeout cancel a request?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Not necessarily. The underlying operation may continue unless its API supports cancellation.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What is a stack trace?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">A stack trace records execution information associated with an error and helps identify where it occurred.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Should I show exception messages directly to users?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Usually not. Technical messages should be translated into clear, safe, user-friendly feedback.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What is a custom API exception?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">It is an application-defined exception representing a specific API-related failure, such as a network error or invalid response.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">How do I implement retry functionality?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Provide a controlled way to repeat a failed operation, ideally with appropriate retry limits and failure classification.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What is FlutterError.onError?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">It is a Flutter framework callback used to report errors caught by the framework.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What is PlatformDispatcher.onError?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">It is a callback for certain unhandled errors on the root isolate that are not caught by the Flutter framework.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Should I use exceptions or Result types?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use exceptions for exceptional failures and consider result types when success and failure are both expected outcomes that callers should handle explicitly.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">How do I test exception handling in Flutter?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Write unit and widget tests covering successful operations, expected exceptions, timeouts, error messages, and retry behavior.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Is exception handling important for production Flutter apps?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Yes. Proper exception handling improves reliability, user experience, maintainability, and debugging.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">24. Conclusion<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Exception handling is an essential skill for professional Dart and Flutter development.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Real applications must deal with unreliable networks, unexpected server responses, invalid data, timeouts, and other operational failures.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In this tutorial, we explored <code>try<\/code>, <code>catch<\/code>, <code>on<\/code>, <code>finally<\/code>, <code>throw<\/code>, <code>rethrow<\/code>, stack traces, and custom exception classes.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">We also learned how to handle asynchronous failures from futures and streams, distinguish technical errors from user-facing messages, and organize error handling across application layers.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Finally, we built a practical Flutter API Error Handling Lab featuring simulated API failures, timeout handling, retry functionality, and automated tests.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The key principle is:<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Handle expected failures gracefully, preserve useful diagnostic information, and make recovery clear to the user.<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">By following these practices, you can build Flutter applications that remain understandable, reliable, and maintainable even when operations fail.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What&#8217;s Next in the Flutter Tutorials Series?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Flutter Article 18: Dart Records, Patterns and Pattern Matching Explained \u2014 Destructuring, Switch Expressions &amp; Practical Flutter Examples (2026 Guide)<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In the next tutorial, we&#8217;ll explore Dart records, pattern matching, destructuring, switch expressions, object patterns, collection patterns, and practical Flutter use cases.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Continue learning Flutter and Dart:<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Moiks Developer Blog:<\/strong> <a href=\"https:\/\/moiks.com\/blog\/\">https:\/\/moiks.com\/blog\/<\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Official Documentation and References<\/h2>\n\n\n\n<ol start=\"1\" class=\"wp-block-list\">\n<li>Dart Error Handling \u2014 <a href=\"https:\/\/dart.dev\/language\/error-handling\" target=\"_blank\" rel=\"noopener\">https:\/\/dart.dev\/language\/error-handling<\/a><\/li>\n\n\n\n<li>Dart Asynchronous Programming \u2014 <a href=\"https:\/\/dart.dev\/language\/async\" target=\"_blank\" rel=\"noopener\">https:\/\/dart.dev\/language\/async<\/a><\/li>\n\n\n\n<li>Dart Futures and Error Handling \u2014 <a href=\"https:\/\/dart.dev\/libraries\/async\/futures-error-handling\" target=\"_blank\" rel=\"noopener\">https:\/\/dart.dev\/libraries\/async\/futures-error-handling<\/a><\/li>\n\n\n\n<li>Dart Streams \u2014 <a href=\"https:\/\/dart.dev\/libraries\/async\/using-streams\" target=\"_blank\" rel=\"noopener\">https:\/\/dart.dev\/libraries\/async\/using-streams<\/a><\/li>\n\n\n\n<li>Dart Exception API \u2014 <a href=\"https:\/\/api.dart.dev\/dart-core\/Exception-class.html\" target=\"_blank\" rel=\"noopener\">https:\/\/api.dart.dev\/dart-core\/Exception-class.html<\/a><\/li>\n\n\n\n<li>Dart StackTrace API \u2014 <a href=\"https:\/\/api.dart.dev\/dart-core\/StackTrace-class.html\" target=\"_blank\" rel=\"noopener\">https:\/\/api.dart.dev\/dart-core\/StackTrace-class.html<\/a><\/li>\n\n\n\n<li>Flutter Error Handling \u2014 <a href=\"https:\/\/docs.flutter.dev\/testing\/errors\" target=\"_blank\" rel=\"noopener\">https:\/\/docs.flutter.dev\/testing\/errors<\/a><\/li>\n\n\n\n<li>Flutter App Architecture \u2014 <a href=\"https:\/\/docs.flutter.dev\/app-architecture\" target=\"_blank\" rel=\"noopener\">https:\/\/docs.flutter.dev\/app-architecture<\/a><\/li>\n\n\n\n<li>Flutter Testing Overview \u2014 <a href=\"https:\/\/docs.flutter.dev\/testing\/overview\" target=\"_blank\" rel=\"noopener\">https:\/\/docs.flutter.dev\/testing\/overview<\/a><\/li>\n\n\n\n<li>DartPad \u2014 <a href=\"https:\/\/dartpad.dev\/\" target=\"_blank\" rel=\"noopener\">https:\/\/dartpad.dev\/<\/a><\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\"><em>Moiks Developer Blog \u2014 Practical Flutter, Dart, Android, and iOS development tutorials.<\/em><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Master Dart exception handling with try, catch, on, finally, rethrow, custom exceptions, and asynchronous error recovery. Build a practical Flutter API Error Handling Lab featuring simulated network failures, timeout handling, retry functionality, friendly error states, and unit and widget tests.<\/p>\n","protected":false},"author":1,"featured_media":510,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"iawp_total_views":0,"footnotes":""},"categories":[353,397],"tags":[558,560,563,394,565,564,561,557,556,559,562],"class_list":["post-509","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-flutter-tutorials","category-dart-programming","tag-dart-custom-exceptions","tag-dart-exception-handling","tag-dart-finally","tag-dart-programming","tag-dart-rethrow","tag-dart-stack-trace","tag-dart-try-catch","tag-flutter-api-errors","tag-flutter-error-handling","tag-flutter-retry","tag-timeoutexception"],"_links":{"self":[{"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/posts\/509","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/comments?post=509"}],"version-history":[{"count":1,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/posts\/509\/revisions"}],"predecessor-version":[{"id":511,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/posts\/509\/revisions\/511"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/media\/510"}],"wp:attachment":[{"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/media?parent=509"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/categories?post=509"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/tags?post=509"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}