Exception handling in Java is a powerful mechanism to handle runtime errors. It allows you to maintain the normal flow of the application even when unexpected errors occur. Java provides five main keywords for exception handling: try
, catch
, throw
, throws
, and finally
.
public class ExceptionExample { public static void main(String[] args) { try { int result = 10 / 0; // ArithmeticException } catch (ArithmeticException e) { System.out.println("Error: " + e.getMessage()); } } }
The try
block contains code that might throw an exception, and the catch
block handles that exception if it occurs. In this case, division by zero results in an ArithmeticException
.
public class ExceptionExample { public static void main(String[] args) { try { throw new Exception("Custom exception"); } catch (Exception e) { System.out.println("Caught exception: " + e.getMessage()); } } }
We can manually throw an exception using the throw
keyword. Here, a custom exception is thrown with the message "Custom exception".
public class ExceptionExample { public static void main(String[] args) { try { System.out.println("Trying..."); } finally { System.out.println("This will always execute"); } } }
The finally
block is always executed, regardless of whether an exception was thrown or not. It is typically used for cleaning up resources.