Junior
How does the try-catch construct work in Java?
sobes.tech AI
Answer from AI
The try-catch construct is used for exception handling — events that disrupt the normal flow of program execution.
- try: A block of code where an exception might potentially occur. If an exception occurs inside the
tryblock, the execution of this block is interrupted. - catch: A block of code that executes if an exception of a specific type (indicated in parentheses after
catch) occurs in the correspondingtryblock. Java searches for an appropriatecatchblock to handle the exception. If found, the code in this block executes. - finally (optional): A block of code that is guaranteed to execute after the try-catch blocks, regardless of whether an exception occurred or was caught. It is used for resource cleanup (closing files, connections, etc.).
public class ExceptionHandlingExample {
public static void main(String[] args) {
try {
// Code that might throw an exception
int result = 10 / 0; // ArithmeticException
System.out.println("This line will not be executed if an exception occurs.");
} catch (ArithmeticException e) {
// Handling the specific exception type
System.err.println("An arithmetic error occurred: " + e.getMessage());
} catch (Exception e) {
// Generic catch for any other exception type
System.err.println("An unknown error occurred: " + e.getMessage());
} finally {
// Code that always executes
System.out.println("Finally block executed.");
}
System.out.println("Program continues after try-catch.");
}
}
Comparison of try-catch and throws:
| Attribute | try-catch | throws |
|---|---|---|
| Purpose | Exception handling | Delegating responsibility |
| Location | Code block | Method signature |
| Action | Catches and handles exceptions | Indicates the possibility of throwing an exception |