Error Handling Python Vs Rust
Error Handling Python Vs Rust
Perfeito. Vou te explicar Error Handling profissional em Rust fazendo paralelo com
Python o tempo todo, porque isso acelera muito a curva de aprendizado.
Python Executar
try:
valor = int("123")
except ValueError as e:
print(f"Erro: {e}")
Rust
Option<T>
[Link] 1/38
11/03/2026, 12:48 Error Handling Python vs Rust
Use quando não há valor, mas isso não é exatamente um erro operacional.
Exemplo em Python
Python Executar
Equivalente em Rust
Rust
Result<T, E>
Representa:
Ok(valor) → sucesso
Err(erro) → falha
Use quando houve uma falha real que precisa ser tratada.
Exemplo em Python
Python Executar
[Link] 2/38
11/03/2026, 12:48 Error Handling Python vs Rust
Equivalente em Rust
Rust
Erro esperado
É algo normal do mundo real:
arquivo não existe
input inválido
parse falhou
conexão recusada
JSON malformado
Ausência esperada
Também normal:
chave não encontrada
item opcional não existe
campo pode ser vazio
[Link] 3/38
11/03/2026, 12:48 Error Handling Python vs Rust
Exemplo:
panic!
unwrap() em contexto muito controlado
Exemplo
Rust
Exemplo
Rust
[Link] 4/38
11/03/2026, 12:48 Error Handling Python vs Rust
Result
Rust
fn main() {
match dividir(10.0, 2.0) {
Ok(resultado) => println!("Resultado: {}", resultado),
Err(erro) => println!("Erro: {}", erro),
}
}
Paralelo em Python
Python Executar
try:
resultado = dividir(10, 2)
print(resultado)
except Exception as e:
print(e)
Option
Rust
fn main() {
let nome = Some("Gandra");
match nome {
Some(valor) => println!("Nome: {}", valor),
None => println!("Sem nome"),
}
}
[Link] 5/38
11/03/2026, 12:48 Error Handling Python vs Rust
Rust
Python
Python Executar
nome = None
valor = nome or "Desconhecido"
unwrap_or_else
Calcula o fallback sob demanda.
Rust
map
Transforma o conteúdo se existir.
Rust
Python
Python Executar
[Link] 6/38
11/03/2026, 12:48 Error Handling Python vs Rust
nome = "gandra"
maiusculo = [Link]() if nome is not None else None
and_then
Encadeia operações que também retornam Option .
Rust
ok_or / ok_or_else
Converte Option em Result .
Rust
Rust
[Link] 7/38
11/03/2026, 12:48 Error Handling Python vs Rust
expect
Mesmo comportamento, mas com mensagem melhor.
Rust
unwrap_or
Rust
unwrap_or_else
Rust
map
Transforma Ok .
Rust
[Link] 8/38
11/03/2026, 12:48 Error Handling Python vs Rust
map_err
Transforma Err .
Rust
println!("{:?}", valor);
and_then
Encadeia operações que retornam Result .
Rust
fn main() {
let resultado = parse_num("10")
.map_err(|e| e.to_string())
.and_then(validar_positivo);
println!("{:?}", resultado);
}
Ideia
Se der Ok , segue.
Se der Err , retorna imediatamente o erro para o chamador.
Exemplo
Rust
use std::num::ParseIntError;
Sem ?
Rust
use std::num::ParseIntError;
Ok(x + y)
}
Paralelo em Python
É como se cada linha pudesse automaticamente “subir” a exception sem escrever
try/except ali.
Python Executar
[Link] 10/38
11/03/2026, 12:48 Error Handling Python vs Rust
8) ? com Option
Também funciona com Option .
Rust
Rust
Funciona.
É bom para exemplos, protótipos e pequenos utilitários.
[Link] 11/38
11/03/2026, 12:48 Error Handling Python vs Rust
Rust
use std::fmt;
#[derive(Debug)]
enum ErroCadastro {
NomeVazio,
IdadeInvalida,
IdadeNegativa,
}
if idade < 0 {
return Err(ErroCadastro::IdadeNegativa);
}
Ok(())
}
Você pode:
[Link] 12/38
11/03/2026, 12:48 Error Handling Python vs Rust
Python Executar
class NomeVazioError(Exception):
pass
class IdadeInvalidaError(Exception):
pass
class IdadeNegativaError(Exception):
pass
Rust
use std::error::Error;
use std::fmt;
#[derive(Debug)]
enum MeuErro {
FalhaParse,
}
Isso é importante quando você quer interoperar com bibliotecas e com tipos genéricos de
erro.
Problema
Sua função chama várias operações que retornam erros diferentes:
std::io::Error
serde_json::Error
ParseIntError
Solução
Criar enum e implementar From .
Rust
use std::fmt;
use std::io;
use std::num::ParseIntError;
#[derive(Debug)]
enum AppError {
Io(io::Error),
Parse(ParseIntError),
}
[Link] 14/38
11/03/2026, 12:48 Error Handling Python vs Rust
Rust
use std::fs;
Rust
use std::error::Error;
use std::fs;
Vantagens
rápido de escrever
aceita muitos tipos de erro
bom para utilitários simples
Desvantagens
perde parte da tipagem específica
menos controle para tratamento detalhado
menos expressivo para domínio de negócio
Regra prática
app pequena / CLI / protótipo: Box<dyn Error> pode ser aceitável
biblioteca / sistema maior / domínio rico: prefira erro customizado
[Link] 15/38
11/03/2026, 12:48 Error Handling Python vs Rust
thiserror
Ótima para criar erros tipados de biblioteca/aplicação.
[Link]
TOML
[dependencies]
thiserror = "2"
Exemplo
Rust
use thiserror::Error;
use std::num::ParseIntError;
use std::io;
#[derive(Debug, Error)]
enum AppError {
#[error("erro de I/O: {0}")]
Io(#[from] io::Error),
Uso:
Rust
use std::fs;
[Link] 16/38
11/03/2026, 12:48 Error Handling Python vs Rust
Ok(valor)
}
Vantagens
menos boilerplate
claro e profissional
ideal para erros tipados
anyhow
Muito boa para aplicações, CLIs e código de alto nível.
[Link]
TOML
[dependencies]
anyhow = "1"
Exemplo
Rust
Ok(valor)
}
Vantagens
ergonomia excelente
adiciona contexto facilmente
ótimo para binários executáveis
muito produtivo
[Link] 17/38
11/03/2026, 12:48 Error Handling Python vs Rust
Desvantagens
não é ideal para API pública de biblioteca
apaga parte da taxonomia precisa do erro
Paralelo em Python
thiserror lembra criar classes específicas de exception
com contexto/log
Erro ruim:
Erro bom:
“falha ao converter campo idade do arquivo [Link]: invalid digit found in string”
Sem biblioteca
Rust
[Link] 18/38
11/03/2026, 12:48 Error Handling Python vs Rust
Com anyhow
Rust
Rust
panic!("estado impossível");
unwrap()
Se falhar, chama panic.
Rust
let x = Some(10).unwrap();
expect()
Mesma ideia, mas com mensagem sua.
Rust
1. Testes
Rust
#[test]
fn teste_parse() {
let n: i32 = "42".parse().unwrap();
assert_eq!(n, 42);
}
2. Protótipos rápidos
Quando evitar
em entrada do usuário
I/O
rede
banco de dados
parsing externo
qualquer coisa sujeita ao mundo real
Regra prática
Se o erro pode acontecer por ação normal do usuário ou do ambiente, não use unwrap() .
Rust
use std::error::Error;
use std::fs;
[Link] 20/38
11/03/2026, 12:48 Error Handling Python vs Rust
Ok(())
}
Paralelo em Python
Seria como deixar a exception propagar até o topo, mas em Rust isso fica explícito e
elegante.
Rust
use std::fs;
Propague quando:
o chamador tem mais contexto
você não consegue decidir a ação correta
quer manter camada limpa
Rust
use std::fs;
use std::io;
[Link] 21/38
11/03/2026, 12:48 Error Handling Python vs Rust
Regra profissional
Camadas baixas propagam. Camadas altas decidem.
CLI
use anyhow
adicione contexto
mostre mensagem amigável no topo
logue detalhes se necessário
API/web backend
erros internos separados de erros públicos
mapeie erro de domínio para HTTP status
nunca exponha detalhes sensíveis
Versão Python
Python Executar
[Link] 22/38
11/03/2026, 12:48 Error Handling Python vs Rust
porta = int(conteudo)
return porta
Rust
use std::fs;
use std::num::ParseIntError;
#[derive(Debug)]
enum ConfigError {
Io(std::io::Error),
Parse(ParseIntError),
FaixaInvalida(u16),
}
[Link] 23/38
11/03/2026, 12:48 Error Handling Python vs Rust
if !(1..=65535).contains(&porta) {
return Err(ConfigError::FaixaInvalida(porta));
}
Ok(porta)
}
Rust
-1
70000
abc
Python
Em Python, int aceita muita coisa e a validação costuma vir depois.
Rust
Em Rust, escolher o tipo certo já elimina classes inteiras de erro.
Essa é uma das maiores mudanças de mentalidade para quem vem de Python.
[Link] 24/38
11/03/2026, 12:48 Error Handling Python vs Rust
Rust
Python
Seria algo parecido com tratar apenas o sucesso, mas Python não tem uma sintaxe
equivalente tão natural.
while let
Útil para consumir fluxo opcional.
Rust
Rust
Exemplo
Converter várias strings em números.
Rust
fn main() {
let entradas = vec!["1", "2", "3"];
println!("{:?}", numeros);
}
Paralelo em Python
Em Python você geralmente faria loop com try/except .
Rust
fn main() {
let entradas = vec!["1", "abc", "3"];
match numeros {
Ok(v) => println!("{:?}", v),
Err(e) => println!("Erro: {}", e),
}
}
[Link] 26/38
11/03/2026, 12:48 Error Handling Python vs Rust
Rust
fn main() {
let entradas = vec!["1", "abc", "3"];
Python
Python Executar
for s in entradas:
try:
[Link](int(s))
except ValueError:
pass
Rust
for r in resultados {
match r {
Ok(v) => println!("Ok: {}", v),
Err(e) => println!("Erro: {}", e),
}
}
[Link] 27/38
11/03/2026, 12:48 Error Handling Python vs Rust
Rust
Rust
#[derive(Debug)]
enum Ambiente {
Dev,
Prod,
}
Uso:
Rust
fn main() {
let amb: Result<Ambiente, _> = "dev".parse();
[Link] 28/38
11/03/2026, 12:48 Error Handling Python vs Rust
println!("{:?}", amb);
}
Paralelo em Python
Python Executar
class Ambiente(Enum):
DEV = "dev"
PROD = "prod"
Camada de infraestrutura
Lê arquivo, banco, rede.
Rust
Camada de domínio
Valida regra de negócio.
Rust
#[derive(Debug)]
enum DominioErro {
NomeVazio,
}
Camada de aplicação
[Link] 29/38
11/03/2026, 12:48 Error Handling Python vs Rust
Rust
#[derive(Debug)]
enum AppError {
Io(std::io::Error),
Dominio(DominioErro),
}
Ideia central
Não misture tudo num erro genérico cedo demais.
Preserve o máximo de estrutura, e só simplifique perto da borda do sistema.
Em aplicação real:
Exemplo conceitual:
Rust
[Link] 30/38
11/03/2026, 12:48 Error Handling Python vs Rust
Recuperável
Result , Option
Irrecuperável
panic!
posso me recuperar?
devo propagar?
isso é bug?
Python deixa isso mais flexível, mas também mais fácil de virar bagunça.
Rust
Rust
[Link] 31/38
11/03/2026, 12:48 Error Handling Python vs Rust
Rust
Em app
Rust
Em trechos internos
? para propagar
Python Executar
if idade < 0:
raise ValueError("idade não pode ser negativa")
[Link] 32/38
11/03/2026, 12:48 Error Handling Python vs Rust
return idade
Rust
Rust
#[derive(Debug)]
enum IdadeErro {
Parse(std::num::ParseIntError),
Negativa,
}
Rust
[Link] 33/38
11/03/2026, 12:48 Error Handling Python vs Rust
Ok(idade)
}
Rust
use thiserror::Error;
use std::fs;
use std::num::ParseIntError;
#[derive(Debug, Error)]
pub enum ConfigError {
#[error("erro de I/O: {0}")]
Io(#[from] std::io::Error),
if !(1..=65535).contains(&porta) {
return Err(ConfigError::PortaInvalida(porta));
}
[Link] 34/38
11/03/2026, 12:48 Error Handling Python vs Rust
Ok(porta as u16)
}
[Link] 35/38
11/03/2026, 12:48 Error Handling Python vs Rust
Python Executar
try:
limite = int(conteudo)
except ValueError as e:
raise ValueError(f"conteúdo inválido em {path}: {conteudo}") from e
if limite <= 0:
raise ValueError("limite deve ser positivo")
return limite
[Link] 36/38
11/03/2026, 12:48 Error Handling Python vs Rust
Rust
if limite <= 0 {
anyhow::bail!("limite deve ser positivo");
}
Ok(limite)
}
Conclusão
A melhor forma de resumir é esta:
modelagem
tipagem
propagação explícita
recuperação controlada
contexto rico
[Link] 37/38
11/03/2026, 12:48 Error Handling Python vs Rust
Posso seguir com uma continuação prática e montar para você um mini projeto real em
Rust mostrando error handling profissional em:
leitura de arquivo
parse de JSON
variáveis de ambiente
HTTP/API
CLI com argumentos
e paralelo completo com Python módulo a módulo.
[Link] 38/38