Exception Handling trong Dart
🎯 Mục tiêu: Xử lý errors với try-catch.
💡 Cú pháp
try {
var result = riskyOperation();
} on FormatException catch (e) {
print("Format error: $e");
} on Exception catch (e) {
print("Exception: $e");
} catch (e, stackTrace) {
print("Error: $e");
print("Stack: $stackTrace");
} finally {
print("Cleanup");
}📝 Throw
void validateAge(int age) {
if (age < 0) {
throw ArgumentError("Age cannot be negative");
}
if (age > 150) {
throw RangeError("Age out of range");
}
}🔧 Custom Exception
class ValidationException implements Exception {
final String message;
ValidationException(this.message);
@override
String toString() => "ValidationException: $message";
}
throw ValidationException("Invalid email");✅ Checklist
-
try-catch-finally -
on Type catchcho specific errors - Custom exceptions với
implements Exception
Last updated on