Sobes.tech
Junior

What to do if an error occurs? Can we catch it and handle it somehow?

sobes.tech AI

Answer from AI

Yes, we can. For error and exception handling in Java, the try-catch-finally mechanism is used.

try {
    // Code that may cause an error (exception)
    int result = 10 / 0; // Example: division by zero
    System.out.println(result);
} catch (ArithmeticException e) {
    // Block executes if an exception of type ArithmeticException or its subclass occurs
    System.err.println("An error occurred during arithmetic operation: " + e.getMessage());
    // You can also log the error, send notifications, etc.
} catch (Exception e) {
    // Block executes if any other exception of type Exception occurs
    System.err.println("A general error occurred: " + e.getMessage());
} finally {
    // Block always executes, regardless of whether an exception occurred or not.
    // Often used for resource cleanup (closing files, connections, etc.)
    System.out.println("Finally block executed.");
}
  • try: Contains code that potentially can generate an exception.
  • catch: Contains code to handle a specific type of exception. You can have multiple catch blocks to handle different exception types (from more specific to more general).
  • finally: Contains code that must be executed in any case (regardless of whether an exception occurred or not).

Besides try-catch-finally, Java also offers:

  • throws: Declaration in the method signature indicating that the method can throw a certain type of exception. This forces the calling code to either handle the exception or also declare it with throws.
  • throw: Used to explicitly throw an exception from the code.
public void readFile(String filename) throws FileNotFoundException {
    // Code that may throw FileNotFoundException
    // ...
    if (!file.exists()) {
        throw new FileNotFoundException("File not found: " + filename);
    }
}

// ... elsewhere in the code ...
try {
    readFile("myFile.txt");
} catch (FileNotFoundException e) {
    System.err.println("Error reading file: " + e.getMessage());
}

Thus, the exception handling mechanism in Java allows catching errors, gracefully terminating program execution, or taking alternative actions to restore functionality.