In Dart, exception handling primarily relies on the keywords try, catch, and finally. The following are the basic steps for handling exceptions:
-
Use the
tryblock: Place code that may throw exceptions within atryblock. -
Catch exceptions:
- Use the
catchblock to catch exceptions. You can specify one or morecatchblocks to handle different types of exceptions. - The
catchblock can receive an exception object, typically namede, and optionally a stack trace object, typically nameds.
Example:
darttry { // Code that may throw an exception } catch (e) { // Handle the exception print('Exception: $e'); }Or more detailed catching:
darttry { // Code that may throw an exception } on SpecificException catch (e) { // Handle specific exception print('Specific exception: $e'); } catch (e, s) { // Handle all other exceptions and print stack trace print('Exception: $e'); print('Stack trace: $s'); } - Use the
-
Use the
finallyblock: The code within thefinallyblock is executed regardless of whether an exception occurred. This is commonly used for resource cleanup, such as closing files or database connections.Example:
darttry { // Code that may throw an exception } catch (e) { // Handle the exception print('Exception: $e'); } finally { // Cleanup code that is always executed print('This is the finally block, executed regardless of exceptions.'); }
Through these mechanisms, you can effectively handle errors and exceptions that may occur during code execution, ensuring the stability and reliability of the program.