Java manipula erros com try/catch/finally e distingue unicamente checked exceptions (devem ser declaradas ou tratadas) de unchecked exceptions (runtime, não obrigadas). Essa distinção é central para a manipulação de erros em Java.
Java manipula erros com try/catch/finally e distingue unicamente checked exceptions (devem ser declaradas ou tratadas) de unchecked exceptions (runtime, não obrigadas). Essa distinção é central para a manipulação de erros em Java.
try {
FileReader f = new FileReader("file.txt"); // may throw IOException
// ... use it ...
} catch (FileNotFoundException e) {
System.out.println("not found: " + e.getMessage()); // specific first
} catch (IOException e) {
System.out.println("io error"); // broader after
} finally {
System.out.println("always runs — cleanup"); // runs no matter what
}
finally sempre é executado (limpeza), mesmo que uma exceção seja lançada ou um return ocorra.
Throwable
├── Error — serious JVM problems (OutOfMemoryError) — don't catch
└── Exception
├── RuntimeException → UNCHECKED (not enforced by the compiler)
│ NullPointerException, IllegalArgumentException, IndexOutOfBounds...
└── (other Exceptions) → CHECKED (compiler enforces handling)
IOException, SQLException...
// MUST either catch it or declare `throws` — the compiler won't let you ignore it
public void readFile() throws IOException { // declare it
Files.readAllLines(Paths.get("file.txt")); // throws checked IOException
}
Checked exceptions (IOException, SQLException) representam condições recuperáveis, esperadas (um arquivo faltante, uma falha de rede). O compilador força você a tratá-las ou declará-las — tornando explícito o tratamento de falhas externas.
// NOT required to declare or catch — usually indicate PROGRAMMING BUGS
String s = null;
s.length(); // NullPointerException (unchecked)
int x = arr[10]; // ArrayIndexOutOfBoundsException (unchecked)
Integer.parseInt("abc"); // NumberFormatException (unchecked)
Unchecked (subclasses de RuntimeException) geralmente sinalizam erros de programação — você corrige o bug em vez de capturá-lo em todo lugar. O compilador não força tratamento.
// resources implementing AutoCloseable are closed automatically
try (FileReader f = new FileReader("file.txt")) {
// use f
} // f.close() called automatically, even on exception — no finally needed
✓ Catch specific exceptions, not bare Exception
✓ Use try-with-resources for files/connections (auto-close)
✓ Don't swallow exceptions silently (empty catch blocks)
✓ Throw meaningful exceptions; include context in messages
✓ Custom exceptions extend Exception (checked) or RuntimeException (unchecked)
A manipulação robusta de erros é essencial, e a distinção checked/unchecked do Java é uma característica definidora (e debatida) que vale a pena entender profundamente.
Checked exceptions forçam o tratamento explícito de falhas externas esperadas (I/O, DB) — promovendo confiabilidade mas às vezes criticada por ser verbosa; unchecked exceptions representam bugs para corrigir em vez de capturar rotineiramente.
Conhecer a hierarquia, quando cada tipo se aplica, a semântica try/catch/finally e o moderno try-with-resources para limpeza automática é fundamental para escrever Java correto e confiável — e para projetar suas próprias exceções apropriadamente.
A distinção molda como as APIs Java são projetadas e é um tópico frequente em entrevistas e revisões de código.