Java
Exception Handling
try-catch-finally and custom exceptions.
By EZ4Code Team
exceptionexception
Code
// try-catch-finally
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.err.println("Arithmetic exception: " + e.getMessage());
} finally {
System.out.println("Always executes");
}
// try-with-resources
try (var reader = new java.io.FileReader("file.txt")) {
int ch;
while ((ch = reader.read()) != -1) {
System.out.print((char) ch);
}
} catch (java.io.IOException e) {
e.printStackTrace();
}
// Custom exception
class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}Explanation
Java exceptions are divided into checked and runtime exceptions; try-with-resources auto-manages resources.
More Java Snippets
String Operations and StringBuilder
Manipulate strings with split, join, substring, and StringBuilder in Java.
Stream API
Process collections using the Stream API.
Lambda Expressions
Simplify code with Lambda expressions.
Optional
Handle null values elegantly.
Collection Operations
Common operations on List, Set, and Map.
File IO
Read and write file operations.