J

Ausnahmebehandlung

Java Syntax Guide

Fehlerbehandlung mit try-catch-Blöcken in Java

Ausnahmebehandlung

Fehlerbehandlung mit try-catch-Blöcken in Java

Java ausnahmebehandlung (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 verwendet try-catch-finally-Blöcke zur Behandlung von Ausnahmen, bei denen es sich um Ereignisse handelt, die den normalen Programmfluss stören. Dies ermöglicht eine elegante Fehlerbehebung.

Common Use Cases

  • Verhindern von Programmabstürzen
  • Behandeln von Datei-I/O-Fehlern
  • Verwalten von Netzwerkkommunikationsproblemen
  • Validieren von Benutzereingaben

Related Java Syntax

Master Ausnahmebehandlung in Java

Understanding Ausnahmebehandlung 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 Ausnahmebehandlung effectively in your Java projects.

Key Takeaways

  • Verhindern von Programmabstürzen
  • Behandeln von Datei-I/O-Fehlern
  • Verwalten von Netzwerkkommunikationsproblemen