Skip to Content
Dart📘 Ngôn ngữ DartException Handling (try-catch)

Exception Handling trong Dart (try-catch)

1. Giới thiệu

Exception handling giúp xử lý lỗi runtime mà không làm crash chương trình.

2. try-catch cơ bản

void main() { try { int result = 10 ~/ 0; // Integer division by zero print(result); } catch (e) { print('Error: $e'); } }

3. Catch exception cụ thể

void main() { try { var list = [1, 2, 3]; print(list[10]); // RangeError } on RangeError { print('Index out of range'); } on FormatException { print('Format error'); } catch (e) { print('Unknown error: $e'); } }

4. Catch với stack trace

void main() { try { throw Exception('Something went wrong'); } catch (e, stackTrace) { print('Error: $e'); print('Stack trace: $stackTrace'); } }

5. finally

void main() { try { print('Opening file...'); throw Exception('File not found'); } catch (e) { print('Error: $e'); } finally { print('Cleaning up...'); // Luôn chạy } }

6. throw và rethrow

void validateAge(int age) { if (age < 0) { throw ArgumentError('Age cannot be negative'); } if (age > 150) { throw RangeError('Age seems unrealistic'); } } void processAge(int age) { try { validateAge(age); } catch (e) { print('Logging error: $e'); rethrow; // Ném lại exception } }

7. Custom Exception

class AuthException implements Exception { final String message; AuthException(this.message); @override String toString() => 'AuthException: $message'; } class NetworkException implements Exception { final int statusCode; final String message; NetworkException(this.statusCode, this.message); @override String toString() => 'NetworkException($statusCode): $message'; } void login(String username, String password) { if (username.isEmpty) { throw AuthException('Username is required'); } if (password.length < 6) { throw AuthException('Password too short'); } }

8. Exception với async/await

Future<String> fetchData() async { await Future.delayed(Duration(seconds: 1)); throw Exception('Network error'); } Future<void> main() async { try { var data = await fetchData(); print(data); } on Exception catch (e) { print('Failed to fetch: $e'); } }

9. Built-in Exceptions

// FormatException - parsing error int.parse('abc'); // RangeError - index out of bounds [1, 2, 3][10]; // ArgumentError - invalid argument Uri.parse(''); // StateError - invalid state [].first; // UnsupportedError - operation not supported List.unmodifiable([1, 2]).add(3);

10. Best Practices

// ✅ Catch specific exceptions try { // code } on FormatException { // handle } on IOException { // handle } // ❌ Tránh catch chung chung try { // code } catch (e) { // không biết loại lỗi } // ✅ Sử dụng finally cho cleanup var file = openFile(); try { processFile(file); } finally { file.close(); }

📝 Tóm tắt

  • try-catch bắt và xử lý exceptions
  • on Type catch exception cụ thể
  • finally luôn chạy dù có lỗi hay không
  • throw ném exception, rethrow ném lại
  • Custom exception implement Exception
Last updated on