try, on, catch, and finally blocks to implement structured exception handling. This mechanism intercepts runtime exceptions thrown within a designated scope, allowing for flow control management, object capture, and resource cleanup.
Syntax Structure
The exception handling structure allows for specific type matching, object capturing, and unconditional execution.Components
The try Block
Defines the lexical scope in which exceptions are monitored. If an exception is thrown within this block, control flow immediately transfers to the nearest matching handler.
The on Clause
Specifies the type of exception to handle. This is used when the handling logic differs based on the class of the thrown exception. Multiple on clauses can be chained; Dart evaluates them in top-down order.
The catch Block
Captures the exception object. This block is required if the handler needs to inspect the value of the exception or access the stack trace. It can be used in conjunction with on or independently to handle all exceptions.
catch accepts up to two positional arguments:
- Exception Object: The actual object thrown (typically a subtype of
ExceptionorError, though Dart allows throwing any non-null object). - StackTrace: An object containing the record of the call stack at the point the exception was thrown.
The finally Block
Contains code that executes unconditionally. The finally block runs after the try and catch blocks complete, regardless of whether an exception was thrown or caught. If the try block exits via return, break, or continue, the finally block executes immediately prior to that exit.
Propagating Exceptions (rethrow)
The rethrow keyword allows a caught exception to be passed up the call stack. Unlike throwing a new exception, rethrow preserves the original exception object and its original stack trace.
Master Dart with Deep Grasping Methodology!Learn More





