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:
-
try-catch-finallyblock:- Code that may throw an exception is placed inside the
tryblock. - The
catchblock catches and handles exceptions of a specific type. Multiplecatchblocks can be used for different exception types. - The
finallyblock 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."); } } } - Code that may throw an exception is placed inside the
-
throwsdeclaration:- A method can declare that it may throw a specific type of exception using the
throwskeyword 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()); } } } - A method can declare that it may throw a specific type of exception using the
-
try-with-resources(since Java 7):- A special form of
tryblock for automatic resource management, where resources implementingAutoCloseableare declared in the parentheses aftertry, 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()); } } } - A special form of
Important points:
- Checked vs. Unchecked Exceptions: In Java, checked exceptions (e.g.,
IOException) must be either caught or declared withthrows, while unchecked exceptions (subclasses ofRuntimeException, 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) orRuntimeException(for unchecked exceptions).