Bỏ qua để đến nội dung

Exception Handling (try-catch)

🎯 Mục tiêu: Xử lý errors với try-catch.


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");
}

void validateAge(int age) {
if (age < 0) {
throw ArgumentError("Age cannot be negative");
}
if (age > 150) {
throw RangeError("Age out of range");
}
}

class ValidationException implements Exception {
final String message;
ValidationException(this.message);
@override
String toString() => "ValidationException: $message";
}
throw ValidationException("Invalid email");

  • try-catch-finally
  • on Type catch cho specific errors
  • Custom exceptions với implements Exception