J
Gestion des Exceptions
Java Syntax Guide
Gestion des erreurs avec des blocs try-catch en Java
Gestion des Exceptions
Gestion des erreurs avec des blocs try-catch en Java
Java gestion des exceptions (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 utilise des blocs try-catch-finally pour gérer les exceptions, qui sont des événements qui perturbent le flux normal d'un programme. Cela permet une récupération d'erreur élégante.
Common Use Cases
- Prévenir les plantages de programme
- Gérer les erreurs d'E/S de fichier
- Gérer les problèmes de communication réseau
- Valider les entrées utilisateur
Related Java Syntax
Master Gestion des Exceptions in Java
Understanding Gestion des Exceptions 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 Gestion des Exceptions effectively in your Java projects.
Key Takeaways
- Prévenir les plantages de programme
- Gérer les erreurs d'E/S de fichier
- Gérer les problèmes de communication réseau