Aspect | try/catch | Result Type |
Usage | Used to catch and handle exceptions | Used to represent success or error conditions |
Syntax | try { … } catch (e) { … } | Result.success(value) or Result.error(e) |
Handling Exceptions | Catch and handle specific types of exceptions | Handle success and error cases explicitly |
Error Information | Provides access to the caught exception | Returns error message or value |
Error Propagation | Exceptions can propagate up the call stack | Explicitly handle errors using when |
Error Type Safety | Requires handling all possible exceptions | Forces explicit handling of success and error |
Code Organization | Requires placing relevant code in try block | Separates success and erro |
Exception Handling with try/catch
try {
// Code that may throw an exception
int result = 10 ~/ 0; // Division by zero
print('Result: $result');
} catch (e) {
// Exception handling
print('Error: $e');
}
Using Result type for error handling
import 'package:dartz/dartz.dart';
Either<String, int> divideNumbers(int a, int b) {
try {
if (b == 0) {
return Left('Error: Division by zero');
}
int result = a ~/ b;
return Right(result);
} catch (e) {
return Left('Error: $e');
}
}
void main() {
Either<String, int> result = divideNumbers(10, 0);
result.fold(
(error) => print(error),
(value) => print('Result: $value'),
);
}
In the first example, a try/catch block is used to handle the exception that may occur during division by zero. The catch block catches the exception and prints the error message.
In the second example, the Either type from the dartz package is used to represent the result as either a left value (error) or a right value (success). The divideNumbers function returns an Either type indicating either the result of the division or an error message. The fold method is used to handle the result by providing separate functions for the left (error) and right (success) cases.
These examples demonstrate different approaches to handle exceptions and errors in Flutter using try/catch and the Result type.