Dart: Exceptions

Carlos Costa

De forma resumida, uma exceção é um evento que ocorre durante a execução de um programa que interrompe o fluxo normal das instruções.

Exemplo:

sum(dynamic x, dynamic y) => x + y;
sum(1, "2");

Executando esse código teremos o seguinte erro:

🚨 Unhandled exception: type ‘String’ is not a subtype of type ‘num’ of ‘other’

Ou seja, o Dart não sabe como somar um número com uma string, então ele lança uma exceção. Podemos tratar essa exceção da seguinte forma:

try {
  print(sum(1, "2"));
} catch (e) {
  print(e);
}

Aqui o dart vai tentar executar o código dentro do bloco try, caso ocorra algum erro ele vai executar o código dentro do bloco catch. Nosso programa não será interrompido e o erro será tratado.

Anatomia do try catch


try {
  throw "Error";
} catch (error) {
  print(error);
} finally {
  print("Done");
}
  • throw - Lança uma exceção.
  • try - Bloco onde o código será executado.
  • catch - Bloco onde o erro será tratado.
  • finally - Bloco que sempre será executado, independente se ocorreu um erro ou não.
  • error - Variável que contém o erro.

Catch multiple exceptions


try {
  throw "Error";
} on String catch (error) {
  print(error);
} on Exception catch (error) {
  print(error);
} catch (error) {
  print(error);
}
  • on - Filtra o tipo de erro que será tratado, caso não seja especificado, qualquer tipo de erro será tratado.

Rethrow


sum(dynamic x, dynamic y) => x + y;

try {
  try {
    sum(1, "2");
  } catch (e) {
    print("First block: $e");
    rethrow;
  }
} catch (e) {
  print("Second block: $e");
}
First block: type 'String' is not a subtype of type 'num' of 'other'
Second block: type 'String' is not a subtype of type 'num' of 'other'
  • rethrow - Lança o erro novamente, para que outro bloco possa tratá-lo.

Custom Exceptions


class CustomException implements Exception {
  final String functionName;
  final String lineNumber;
  final String message;

  CustomException({
    required this.message,
    required this.functionName,
    required this.lineNumber,
  });
}

void main(List<String> args) {
  add(dynamic x, dynamic y) {
    if (x is int && y is int) {
      return x + y;
    }

    throw new CustomException(
      message: "Message: The value must be integer",
      functionName: "Function name: add",
      lineNumber: "Line number: 12",
    );
  }

  try {
    print(add(1, "2"));
  } on CustomException catch (e) {
    print(e.message);
    print(e.functionName);
    print(e.lineNumber);
  }
}

Executando o exemplo acima teremos o seguinte resultado: 👇

Message: The value must be integer
Function name: add
Line number: 12

Nesse exemplo, criamos uma classe que herda de Exception e criamos um método add que lança essa exceção caso os valores passados não sejam inteiros.

Referências