For AI agents: A markdown version of this page is available at https://docs.datadoghq.com/security/code_security/static_analysis/static_analysis_rules/dart-code-quality/use-rethrow-when-possible.md. A documentation index is available at /llms.txt.

Use rethrow to rethrow a caught exception

This product is not supported for your selected Datadog site. ().

Metadata

ID: dart-code-quality/use-rethrow-when-possible

Language: Dart

Severity: Notice

Category: Code Style

Description

Throwing the caught exception object directly (for example throw e) inside its own catch block resets the stack trace and discards the original error origin, which makes debugging harder. Use rethrow instead to preserve the original exception and its stack trace.

Non-Compliant Code Examples

void main() {
  try {
    risky();
  } catch (e) {
    throw e;
  }

  try {
    risky();
  } on Exception catch (e, s) {
    throw e;
  }
}

void risky() {}

Compliant Code Examples

void main() {
  try {
    risky();
  } catch (e) {
    rethrow;
  }

  try {
    risky();
  } catch (e) {
    throw StateError('x');
  }

  try {
    risky();
  } catch (e) {
    throw other;
  }

  try {
    risky();
  } on Exception catch (e, s) {
    throw e.inner;
  }
}

var other = Exception('boom');

void topLevel() {
  throw e;
}

void risky() {}
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Seamless integrations. Try Datadog Code Security