Exception Handling (try-catch)
🎯 Mục tiêu: Xử lý errors với try-catch.
💡 Cú pháp
Phần tiêu đề “💡 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
Phần tiêu đề “📝 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
Phần tiêu đề “🔧 Custom Exception”class ValidationException implements Exception { final String message; ValidationException(this.message);
@override String toString() => "ValidationException: $message";}
throw ValidationException("Invalid email");✅ Checklist
Phần tiêu đề “✅ Checklist”-
try-catch-finally -
on Type catchcho specific errors - Custom exceptions với
implements Exception