Can you explain the concept of exception handling in Java? Provide examples of try-catch blocks.
Exception handling in Java allows developers to gracefully handle errors during program execution. The "try-catch" block is used to catch and handle exceptions.
public class Example { public static void main(String[] args) { try { int result = 10 / 0; // Example of an exception } catch (ArithmeticException e) { System.out.println("An arithmetic exception occurred: " + e.getMessage()); } } }
In this example, the "try" block attempts to perform a division by zero, which results in an ArithmeticException
. The corresponding "catch" block handles this exception by printing an error message.