How can exceptions be handled in Java?
sobes.tech AI
Answer from AI
Exception handling in Java is performed using the following constructs:
-
try-catchblocks:The
tryblock contains code that may generate an exception. Thecatchblock(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()); } -
finallyblock: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"); } -
throwkeyword:Used to explicitly create and throw an exception.
if (value < 0) { throw new IllegalArgumentException("Value cannot be negative"); } -
throwskeyword: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
tryconstruct for automatic resource management, implementing theAutoCloseableinterface. Resources are automatically closed at the end of thetryblock.try (FileInputStream fis = new FileInputStream("example.txt")) { // Working with resource fis } catch (IOException e) { // Handling IOException }