Flutter如何自定义Exception

在Flutter开发中遇到需要自定义异常的情况,该如何实现?比如想根据业务需求创建特定的错误类型,并能够像内置异常一样通过try-catch捕获。请问具体步骤是什么?是否需要继承某个基类?能否提供代码示例说明如何定义、抛出和捕获自定义异常?

2 回复

在Flutter中自定义Exception,只需继承Exception类并重写toString方法。例如:

class CustomException implements Exception {
  final String message;
  CustomException(this.message);
  
  @override
  String toString() => 'CustomException: $message';
}

使用时通过throw CustomException('错误信息')抛出异常。

更多关于Flutter如何自定义Exception的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在Flutter中自定义Exception可以通过创建继承自Exception类的自定义异常类来实现。以下是具体步骤和示例:

1. 基础自定义异常类

class CustomException implements Exception {
  final String message;
  final int errorCode;
  
  const CustomException(this.message, [this.errorCode = 0]);
  
  @override
  String toString() {
    return 'CustomException: $message (Error Code: $errorCode)';
  }
}

2. 更具体的异常子类

// 网络异常
class NetworkException extends CustomException {
  NetworkException(String message, int errorCode) 
    : super(message, errorCode);
}

// 数据解析异常
class ParseException extends CustomException {
  ParseException(String message) : super(message, 1001);
}

// 认证异常
class AuthException extends CustomException {
  AuthException(String message) : super(message, 401);
}

3. 使用示例

void fetchData() {
  try {
    // 模拟抛出自定义异常
    throw NetworkException('Connection timeout', 408);
  } on NetworkException catch (e) {
    print('Network error: ${e.message}');
  } on CustomException catch (e) {
    print('Custom error: ${e.toString()}');
  } catch (e) {
    print('Unknown error: $e');
  }
}

4. 最佳实践建议

  • 明确的错误信息:提供清晰的错误描述
  • 错误代码:包含错误代码便于处理
  • 分层设计:根据业务需求创建不同层级的异常类
  • 合理使用:只在真正异常情况下使用,不要用于控制流程

这样设计可以让错误处理更加结构化和可维护。

回到顶部