J
Tratamento de Exceções
Java Syntax Guide
Tratamento de erros com blocos try-catch em Java
Tratamento de Exceções
Tratamento de erros com blocos try-catch em Java
Java tratamento de exceções (java)
import java.io.*;
import java.util.Scanner;
public class ExceptionHandlingDemo {
public static void main(String[] args) {
try {
// Multiple operations that might throw exceptions
readFile("example.txt");
divideNumbers(10, 0);
processArray(null);
} catch (FileNotFoundException e) {
System.out.println("File not found: " + e.getMessage());
} catch (ArithmeticException e) {
System.out.println("Math error: " + e.getMessage());
} catch (NullPointerException e) {
System.out.println("Null pointer: " + e.getMessage());
} catch (Exception e) {
// Catch-all for unexpected exceptions
System.out.println("Unexpected error: " + e.getMessage());
} finally {
// Always executed
System.out.println("Cleanup completed");
}
// Try-with-resources (Java 7+)
try (Scanner scanner = new Scanner(System.in);
FileWriter writer = new FileWriter("output.txt")) {
System.out.print("Enter your name: ");
String name = scanner.nextLine();
writer.write("Hello, " + name + "!");
} catch (IOException e) {
System.out.println("IO Error: " + e.getMessage());
}
}
// Method that throws checked exception
public static void readFile(String filename) throws FileNotFoundException {
File file = new File(filename);
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
scanner.close();
}
// Method that throws unchecked exception
public static int divideNumbers(int a, int b) {
if (b == 0) {
throw new ArithmeticException("Division by zero");
}
return a / b;
}
// Method that might throw NullPointerException
public static void processArray(String[] array) {
if (array == null) {
throw new NullPointerException("Array cannot be null");
}
System.out.println("Array length: " + array.length);
}
}
// Custom exception class
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}
class PersonValidator {
public static void validateAge(int age) throws InvalidAgeException {
if (age < 0) {
throw new InvalidAgeException("Age cannot be negative");
}
if (age > 150) {
throw new InvalidAgeException("Age seems unrealistic");
}
}
public static void main(String[] args) {
try {
validateAge(-5);
} catch (InvalidAgeException e) {
System.out.println("Validation error: " + e.getMessage());
}
}
}
Explanation
Java usa blocos try-catch-finally para lidar com exceções, que são eventos que interrompem o fluxo normal de um programa. Isso permite recuperação de erro elegante.
Common Use Cases
- Prevenir travamentos de programa
- Lidar com erros de E/S de arquivo
- Gerenciar problemas de comunicação de rede
- Validar entrada do usuário
Related Java Syntax
Master Tratamento de Exceções in Java
Understanding Tratamento de Exceções is fundamental to writing clean and efficient Java code. This comprehensive guide provides you with practical examples and detailed explanations to help you master this important concept.
Whether you're a beginner learning the basics or an experienced developer looking to refresh your knowledge, our examples cover real-world scenarios and best practices for using Tratamento de Exceções effectively in your Java projects.
Key Takeaways
- Prevenir travamentos de programa
- Lidar com erros de E/S de arquivo
- Gerenciar problemas de comunicação de rede