Sobes.tech
Junior

How can exceptions be handled in Java?

sobes.tech AI

Answer from AI

In Java, exceptions are handled using the try-catch-finally construct or by declaring that a method may throw an exception using throws.

Main methods:

  1. try-catch-finally block:

    • Code that may throw an exception is placed inside the try block.
    • The catch block catches and handles exceptions of a specific type. Multiple catch blocks can be used for different exception types.
    • The finally block always executes, regardless of whether an exception was thrown or not. It is used for resource cleanup (e.g., closing streams).
    class Example {
        public static void main(String[] args) {
            try {
                // Code that may throw an exception
                int result = 10 / 0; // Example of division by zero
            } catch (ArithmeticException e) {
                // Handling ArithmeticException
                System.err.println("Error: division by zero.");
                e.printStackTrace(); // Print stack trace
            } catch (Exception e) {
                // Handling any other exception
                System.err.println("Another error occurred.");
                e.printStackTrace();
            } finally {
                // Code that always runs
                System.out.println("Finally block executed.");
            }
        }
    }
    
  2. throws declaration:

    • A method can declare that it may throw a specific type of exception using the throws keyword in its signature. This shifts the responsibility of handling the exception to the caller.
    class Example {
        public static void readFile(String path) throws java.io.IOException {
            // Code that may throw IOException
            java.io.FileInputStream fis = new java.io.FileInputStream(path);
            // ...
        }
    
        public static void main(String[] args) {
            try {
                readFile("nonexistent_file.txt");
            } catch (java.io.IOException e) {
                System.err.println("Error reading file: " + e.getMessage());
            }
        }
    }
    
  3. try-with-resources (since Java 7):

    • A special form of try block for automatic resource management, where resources implementing AutoCloseable are declared in the parentheses after try, and are automatically closed at the end of the block, regardless of exceptions.
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    
    class Example {
        public static void main(String[] args) {
            try (BufferedReader br = new BufferedReader(new FileReader("my_file.txt"))) {
                // Working with the resource (BufferedReader)
                String line;
                while ((line = br.readLine()) != null) {
                    System.out.println(line);
                }
            } catch (IOException e) {
                // Handling IOException
                System.err.println("Error reading file: " + e.getMessage());
            }
        }
    }
    

Important points:

  • Checked vs. Unchecked Exceptions: In Java, checked exceptions (e.g., IOException) must be either caught or declared with throws, while unchecked exceptions (subclasses of RuntimeException, e.g., NullPointerException, ArithmeticException) do not require explicit handling.
  • Exception chaining: You can create exception chains by wrapping one exception into another (throw new Exception("Message", originalException)). This helps preserve the original cause of the error.
  • Custom exceptions: You can create your own exception classes by inheriting from Exception (for checked exceptions) or RuntimeException (for unchecked exceptions).