Sobes.tech
Junior

How can exceptions be handled in Java?

sobes.tech AI

Answer from AI

Exception handling in Java is performed using the following constructs:

  • try-catch blocks:

    The try block contains code that may generate an exception. The catch block(s) catch and handle exceptions of a specific type.

    try {
        // Code that potentially throws an exception
        int result = 10 / 0;
    } catch (ArithmeticException e) {
        // Handling ArithmeticException
        System.err.println("Division by zero error: " + e.getMessage());
    } catch (Exception e) {
        // Handling any other exceptions (more general type)
        System.err.println("A general error occurred: " + e.getMessage());
    }
    
  • finally block:

    Always executes, regardless of whether an exception was thrown or not. Used for resource cleanup (closing files, connections, etc.).

    try {
        // Code that may throw an exception
    } catch (IOException e) {
        // Handling IOException
    } finally {
        // Code that must execute in any case
        System.out.println("Finally block executed");
    }
    
  • throw keyword:

    Used to explicitly create and throw an exception.

    if (value < 0) {
        throw new IllegalArgumentException("Value cannot be negative");
    }
    
  • throws keyword:

    Used in method signatures to indicate that the method may throw one or more exceptions. The calling code must either handle these exceptions or declare them with throws.

    public void readFile(String filename) throws IOException {
        // Code that may throw IOException
        // ...
    }
    
  • Try-with-resources:

    A special try construct for automatic resource management, implementing the AutoCloseable interface. Resources are automatically closed at the end of the try block.

    try (FileInputStream fis = new FileInputStream("example.txt")) {
        // Working with resource fis
    } catch (IOException e) {
        // Handling IOException
    }
    
How can exceptions be handled in Java? — Java - sobes.tech