Java Exception Handling Best Practices

1. Specific Exceptions Catch Karo

Generic Exception ke bajaye specific exception types ko catch karo, taaki error ki prakriti samajhna aur debug karna aasan ho.

try {
  // Risky code
} catch (IOException e) {
  System.out.println("File error: " + e.getMessage());
} catch (NumberFormatException e) {
  System.out.println("Number format error: " + e.getMessage());
}

2. Sirf Samajh Ke Exceptions Handle Karo

Empty catch blocks se bacho, jisme exception ignore kiya jata hai. Ye bugs ko chhupata hai aur debugging mushkil kar deta hai.

try {
  int result = 10 / 0;
} catch (ArithmeticException e) {
  System.out.println("Zero se divide allowed nahi hai!");
}

3. Resources Close Karna Na Bhulo

File aur database connections jaise resources ko try-with-resources ya finally block me close karo taaki resource leak naa ho.

try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
  String line = br.readLine();
  System.out.println(line);
} catch (IOException e) {
  e.printStackTrace();
}

4. Clear Aur Useful Exception Messages

Exception messages ko clear aur detailed rakho jisse samasya ko jaldi samjha ja sake.

5. Exceptions Ko Sahi Level Par Handle Karo

Exceptions ko us jagah handle karo jaha recovery possible ho ya user ko sahi message diya ja sake. Agar handle na kar pao to caller tak propagate karo.

6. Logging Ka Prayog Karo

System.out.println se acha logging framework (SLF4J, Log4J) use karo jisse ki logs structured aur trackable rahe.

7. Global Exception Handler Karo Setup

Application me centralized global exception handler rakho jo uncaught exceptions ko gracefully handle kare.

8. Checked aur Unchecked Exceptions Ka Sahi Prayog

Checked exceptions sqlalchemy situations ke liye hain jahan seekh milti hai ki exceptions ko handle karna hai; unchecked exceptions programming mistakes ko detect karte hain.

Example Code:

import java.io.*;

public class ExceptionBestPractice {
    public static void readFile(String filename) throws IOException {
        try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
            String line = br.readLine();
            System.out.println("First line: " + line);
        }
    }

    public static void main(String[] args) {
        try {
            readFile("data.txt");
        } catch (FileNotFoundException e) {
            System.err.println("File nahi mila: " + e.getMessage());
        } catch (IOException e) {
            System.err.println("IO exception aayi: " + e.getMessage());
        } catch (Exception e) {
            System.err.println("Unknown error: " + e.getMessage());
        } finally {
            System.out.println("Exception handling complete hua.");
        }
    }
}